Select2 doesn't show selected value
Asked Answered
A

13

42

Select2 loads all items from my list successful, the issue I found when try to select a specific value when page loads. Example:

:: put select2 in a specific html element, no value is selected even all items are loaded.

$('#my_id').select2();

:: When the page is loaded I'm trying to show a specific item selected, but doesn't work as expected, because even selected, the select2 doesn't show it.

$('#my_id').val('3'); //select the right option, but doesn't render it on page loads.

How to make a selected option to pop up when pages loads?

Thanks in advance.

#UPDATED

:: How I load all select2 items (sorry, its jade, not pure HTML):

label(for='category') Category
    span.required *
select(id='category', style='width:230px', name='category')
    option(value='') - Select -
    each cat in categories
        option(value='#{cat.id}') #{cat.description}

P.S.: All items from my list are loaded.

:: How I initialize the select2:

Just put the following line code on my javascript and it does successful:

$('#category').select2();

:: How I'm trying to select a specific value:

  • First attempt:

      $('#category').select2(
          {
              initSelection: function(element, callback) {
                  callback($('#field-category').val());
              }
          }
      );
    
  • Second attempt:

      $('#category').val($('#field-category').val());
    

P.S.: #field-category has a value its a hidden input field and works OK.

Asteriated answered 19/2, 2013 at 12:23 Comment(3)
Is "3" the value for the option that you want to select? Have you wrapped the code in a document ready function?Hasdrubal
Can you share the mark up/data for the select2Rivi
@Asteriated See my updated answer, looks like no need to use initSelectionRivi
R
60

You need to use the initSelection option to set the initial value.

If you are using a pre-defined select element to create the select2, you can use the following method

$('select').select2().select2('val','3')

Demo: Fiddle

Rivi answered 19/2, 2013 at 12:28 Comment(9)
I've tried initSelection before, maybe my code is wrong. I'll show hereAsteriated
Thanks Arun, worked for me. When page loads, select2 is loaded with a specific value.Asteriated
Nice code, btw I want to understand why I have to use select2() twice?Asteriated
It is because, I didn't find a way to pass the initial value to the select2. so I'm creating the select2 using the first call and then set the value using the second call.Rivi
Thanks, Arun, maybe it's a bug from the component.Asteriated
@ArunPJohny Can you maybe help with the initial selection in BackboneForms?Receiptor
@ArunPJohny Please correct me if I'm wrong. I tried the fiddle example using your link but it doesn't seem to work, the default value there should be Three right ? but it shows always One.Circumambient
@Circumambient see now - jsfiddle.net/arunpjohny/AeXYN - the plugin js files was relocated so there were errorsRivi
This is now deprecated in favor of the other answer in Select2 4.0.0 and will likely stop working entirely in Select2 4.1.0.Linehan
C
37

add a trigger change after setting val:

$('#my_id').val('3').trigger('change');
Counts answered 11/11, 2014 at 3:42 Comment(3)
This is now the recommended way of setting the value in 4.0.0, as it works consistently and matches a normal <select>.Linehan
What if I don't want to trigger change and still have it show?Caldera
But what if I've attached something to "select2:select" and not change? Doing the above doesnt work.Horseshoe
S
5

A very simple way to tackle this problem is :

//Step1: Here assuming id of your selectbox is my_id, so this will add selected attribute to 1st option
$('#my_id option').eq(0).prop('selected',true);

//Step2: Now reinitialize your select box

//This will work, if you haven't initialized selectbox
$('#my_id').select2(); 

or

//This will work, if you have initialized selectbox earlier, so destroy it first and initialise it
$('#my_id').select2('destroy').select2();
Stork answered 13/2, 2018 at 6:25 Comment(0)
A
5

This may help:

$('#mySelect2').val('1'); // Select the option with a value of '1'
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed

You can find more on details here:

Thanks

Archeology answered 3/1, 2019 at 2:18 Comment(0)
H
1

If you are using select2 v4.0.0 or above, you can check select2 documentation

// Initialize select2 for all select tags
$('select').select2();

// Initialize select2 for a specific id
$('#my-id').select2();

// Initialize select2 for a class
$('.my-class').select2();

// Update the displayed value after changing the selected option.
$('#my-id').trigger('change');
Hackathorn answered 29/5, 2022 at 12:30 Comment(1)
Thanks for sharing this. Actually what worked is triggering the change event here. $('#my-id').trigger('change');Collagen
E
0

Here is how to make val in select2 just select the corresponding element. For some reason, select2 doesn't provide the function to look up selections by id.

init:

$("#thing").select2({data:sources, initSelection: function(item, callback) {
  // despite select2 having already read the whole sources list when you 
  // do .val(n) you have to explicitly tell it how to find that item again.
  var to_be_selected = null;
  $.each(sources, function(index, thing) {
    if (thing.id == item.val()) {
      to_be_selected = thing;
      return;
    }
  })
  callback(to_be_selected);
}})

normal code

// to load the thing with id==3 from the initial sources list.
$("#thing").select2({'val': 3})
Export answered 23/6, 2013 at 6:4 Comment(2)
maybe it's {val:3} not {'val', 3} ?Counts
{val: 3} (not a real option) and {val, 3} (invalid syntax) won't actually work. You might get lucky if Select2 reinitializes itself, but that's a lucky side effect in the long run.Linehan
B
0

Per here initSelection is deprecated in Select2 4.0 and later.

Using Select2 4.0.0 this worked for me:

$('#my_id').select2({val:3});

HT: @Kokizzu

Betancourt answered 4/5, 2015 at 19:7 Comment(1)
val isn't even a valid option for Select2, this works because calling .select2() completely re-initializes Select2 (which ends up detecting the new selected value).Linehan
Z
0

I meet with the same problem, this works for me:

Using Select2 > 4.0.0
$('#select_id').val('3').trigger('change');
Zilla answered 7/7, 2016 at 3:31 Comment(0)
P
0

For me I was sending selected in the data set still default option was not getting selected. I had to do something like below to make it work -

$(".select").select2({
    data: data_names
});
data_names.forEach(function(name) {
    if (name.selected) {
        $(".select").select2('val', name.id);
    }
});
Polypeptide answered 10/12, 2017 at 16:35 Comment(0)
R
0

I had a multiple select2 box with multiple selections.

Step 1 was to put my string of school_ids into an array of integers corresponding to the id of each school, and remove a leading zero. I had to do this in a separate script tag.

<script>
    var school_ids = <%= raw JSON.parse(@search.school_ids).map{|x| x.to_i} - [0]%>
</script>

Step two was to create the select box, then set the values, then trigger like so:

<script>
$(document).ready(function() {
        $('.select2-multiple').select2({
            placeholder: "Hit Enter After Selection",
            width: 'resolve'
        });
        $('.select2-multiple').val(school_ids);
        $('.select2-multiple').trigger('change');
</script>
Ragman answered 22/5, 2019 at 2:10 Comment(0)
K
0

trigger just select2 to set the value

$('#my_id').val('3').trigger("change.select2");

and this will trigger select2 with dropdown

$('#my_id').val('3').trigger("change");
Keir answered 19/2, 2020 at 15:44 Comment(0)
S
0
  var option=$(this);
   if(option.val()==data.StudentCourses.CourseId)
   {
    option.setAttribute('Selected');
   }
   });

i have initilized select2 because i just want few options selected from them.

Sartin answered 6/10, 2020 at 6:56 Comment(0)
F
0
    $('.classname').each(function() {
     $(this).siblings().find('.select2selection__rendered').text($(this).text())
    })

in my case I were dealing with a class then I used this way to set showing content at select2

  <option selected value="your_value">your_text</option>

u need to put this at each select box's first option

Fascicle answered 7/7, 2022 at 6:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.