JQuery select2 set default value from an option in list?
I want to be able to set the default/selected value of a select element using the JQuery Select2 plugin.
One more way - just add a selected = "selected"
attribute to the select
markup and call select2
on it. It must take your selected value. No need for extra JavaScript. Like this :
Markup
<select class="select2">
<option id="foo">Some Text</option>
<option id="bar" selected="selected">Other Text</option>
</select>
JavaScript
$('select').select2(); //oh yes just this!
See fiddle : http://jsfiddle.net/6hZFU/
Edit: (Thanks, Jay Haase!)
If this doesn't work, try setting the val
property of select2
to null
, to clear the value, like this:
$('select').select2("val", null); //a lil' bit more :)
After this, it is simple enough to set val
to "Whatever You Want"
.
The above solutions did not work for me, but this code from Select2's own website did:
$('select').val('US'); // Select the option with a value of 'US'
$('select').trigger('change'); // Notify any JS components that the value changed
Webpage found here
Hope this helps for anyone who is struggling, like I was.
$("#id").select2("val", null); //this will not work..you can try
You should actually do this...intialise and then set the value..well this is also the way it worked for me.
$("#id").select2().select2("val", null);
$("#id").select2().select2("val", 'oneofthevaluehere');