38
votes

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.

Thanks, guys!

11
Is "3" the value for the option that you want to select? Have you wrapped the code in a document ready function? – Johan
Can you share the mark up/data for the select2 – Arun P Johny
@Ito See my updated answer, looks like no need to use initSelection – Arun P Johny

11 Answers

54
votes

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

32
votes

add a trigger change after setting val:

$('#my_id').val('3').trigger('change');
4
votes

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();
3
votes

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

0
votes

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

0
votes

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})
0
votes

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);
    }
});
0
votes

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>
0
votes

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");
0
votes

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

Using Select2 > 4.0.0
$('#select_id').val('3').trigger('change');
0
votes
  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.