Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 doesn't show selected value

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!

like image 391
Ito Avatar asked Feb 19 '13 12:02

Ito


2 Answers

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

like image 184
Arun P Johny Avatar answered Nov 03 '22 15:11

Arun P Johny


add a trigger change after setting val:

$('#my_id').val('3').trigger('change'); 
like image 44
Kokizzu Avatar answered Nov 03 '22 16:11

Kokizzu