Home > Backend Development > PHP Tutorial > 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
Release: 2024-10-31 19:27:01
Original
751 people have browsed it

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>
Copy after login

Using jQuery:

<code class="js">var $newOption = $("<option selected='selected'></option>").val("TheID").text("The text")

$("#myMultipleSelect2").append($newOption).trigger('change');</code>
Copy after login

Select2 Version Below V4

  1. HTML:

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

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

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

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>
Copy after login
<code class="js">$('[name=mySelect2]').val("0"); // Select "One"
$("#mySelect2").select2("val", "0"); // Equivalent</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template