Home > Article > Backend Development > How to Set Selected Values in jQuery Select2 for Different Versions?
In Select2 version 4 and above, you can directly append pre-selected options to your select element:
<code class="html"><select id="myMultipleSelect2" multiple="" name="myMultipleSelect2[]"> <option value="TheID" selected="selected">The text</option> </select> </code>
Using jQuery:
<code class="js">var $newOption = $("<option selected='selected'></option>").val("TheID").text("The text") $("#myMultipleSelect2").append($newOption).trigger('change');</code>
HTML:
<code class="html"><input name="mySelect2" type="hidden" id="mySelect2"></code>
Create Select2 Instance:
<code class="js">$("#mySelect2").select2({ placeholder: "My Select 2", multiple: false, minimumInputLength: 1, ajax: {...}, ... });</code>
Set Selected Value:
<code class="js">$("#mySelect2").select2('data', { id:"elementID", text: "Hello!" });</code>
<code class="html"><select name="mySelect2" id="mySelect2"> <option value="0">One</option> <option value="1">Two</option> <option value="2">Three</option> </select></code>
<code class="js">$('[name=mySelect2]').val("0"); // Select "One" $("#mySelect2").select2("val", "0"); // Equivalent</code>
The above is the detailed content of How to Set Selected Values in jQuery Select2 for Different Versions?. For more information, please follow other related articles on the PHP Chinese website!