I want to be able to set the default/selected value of a select element using the JQuery Select2 plugin.
New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).
Your best option is to use the placeholder support in Select2 and include a blank option tag as your default selection.
HTML. Create a <select class="select2_el" > element to initialize select2 on page load and create <div id="elements" > container to store <select > element on button click using jQuery AJAX.
Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.
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"
.
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