JQuery select2 set default value from an option in list?

user857276 picture user857276 · Jun 6, 2013 · Viewed 175.1k times · Source

I want to be able to set the default/selected value of a select element using the JQuery Select2 plugin.

Answer

krishwader picture krishwader · Jun 6, 2013

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".