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