Home >Backend Development >PHP Tutorial >How to Pre-Select a Value in Select2: A Guide for Versions 4 and Below?
Select2 is a jQuery plugin that provides a customizable select box widget. In this article, we'll explore how to set a pre-selected value in Select2.
<code class="html"><input type="hidden" name="programid" id="programid" class="width-500"><ol start="2"> <li> <strong>Initialize Select2:</strong> Create an instance of Select2 and configure it with the necessary options, including an AJAX call for retrieving data.</li> <li> <strong>Set Pre-Selected Value:</strong> Use the select2('data', { id: "selectedID", text: "selectedText" }) method to set the selected value.</li> </ol> <h3>Select2 Version 4 and above</h3> </h3> <p>For Select2 v4 and above, the approach differs slightly:</p> <ol><li> <strong>HTML:</strong> Define the Select2 input field as a standard select element with options and a selected attribute:</li></ol> <pre class="brush:php;toolbar:false"><code class="html"><select id="mySelect2" name="mySelect2[]"> <option value="TheID" selected="selected">The text</option> </select></code>
<code class="javascript">var $newOption = $("<option selected='selected'></option>").val("TheID").text("The text"); $("#mySelect2").append($newOption).trigger('change');</code>
<code class="javascript">$("#mySelect2").val(5).trigger('change');</code>
These methods provide a straightforward way to set a pre-selected value in Select2, regardless of the version you're using.
The above is the detailed content of How to Pre-Select a Value in Select2: A Guide for Versions 4 and Below?. For more information, please follow other related articles on the PHP Chinese website!