Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 576
user857276 Avatar asked Jun 06 '13 18:06

user857276


People also ask

How do I set Select2 values?

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

How do I stop Select2 from auto selecting the first option?

Your best option is to use the placeholder support in Select2 and include a blank option tag as your default selection.

How do I create a Select2 dynamically?

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.

What does Select2 () do?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.


1 Answers

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

like image 120
krishwader Avatar answered Sep 16 '22 18:09

krishwader