Home  >  Article  >  Backend Development  >  How to Programmatically Set the Selected Value in jQuery Select2?

How to Programmatically Set the Selected Value in jQuery Select2?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 16:58:02129browse

How to Programmatically Set the Selected Value in jQuery Select2?

How to set selected value of jQuery Select2?

jQuery Select2 is a popular plugin that enhances the usability of select elements. One of its useful features is the ability to programmatically set the selected value. This can be particularly helpful in scenarios where a predefined value needs to be displayed upon initial page load or when editing previously saved selections.

Select2 < V4

Step 1: HTML Markup

Include a hidden input field to hold the selected value:

<code class="html"><input type="hidden" name="mySelect2" id="mySelect2"></h3>
<p><strong>Step 2: Create a Select2 Instance</strong></p>
<p>Initialize Select2 with the appropriate options:</p>
<pre class="brush:php;toolbar:false"><code class="js">$("#mySelect2").select2({
  placeholder: "My Select 2",
  multiple: false,
  minimumInputLength: 1,
  ajax: {
    url: "/elements/all",
    dataType: 'json',
    quietMillis: 250,
    data: function(term, page) {
      return {
        q: term,
      };
    },
    results: function(data, page) {
      return { results: data };
    },
    cache: true
  },
  formatResult: function(element){
    return element.text + ' (' + element.id + ')';
  },
  formatSelection: function(element){
    return element.text + ' (' + element.id + ')';
  },
  escapeMarkup: function(m) {
    return m;
  }
});</code>

Step 3: Set the Desired Value

Use the data() method to set the selected value:

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

Select2 V4

Using HTML

For Select2 v4, you can directly append a selected option to the 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>

Directly Setting Value

<code class="js">$("#myMultipleSelect2").val(5).trigger('change');</code>

The above is the detailed content of How to Programmatically Set the Selected Value in jQuery Select2?. 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