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.
:: 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!
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
add a trigger change after setting val:
$('#my_id').val('3').trigger('change');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With