Home  >  Article  >  Backend Development  >  How to Set Selected Values in jQuery Select2 for Different Versions?

How to Set Selected Values in jQuery Select2 for Different Versions?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 19:27:01663browse

How to Set Selected Values in jQuery Select2 for Different Versions?

Setting Selected Value in jQuery Select2

Select2 Version V4 and Above

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>

Select2 Version Below V4

  1. HTML:

    <code class="html"><input name="mySelect2" type="hidden" id="mySelect2"></code>
  2. Create Select2 Instance:

    <code class="js">$("#mySelect2").select2({
       placeholder: "My Select 2",
       multiple: false,
       minimumInputLength: 1,
       ajax: {...},
       ...
    });</code>
  3. Set Selected Value:

    <code class="js">$("#mySelect2").select2('data', { id:"elementID", text: "Hello!" });</code>

Non-AJAX Select2

<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn