Select2 is a popular jQuery plugin used to create customizable and flexible dropdown lists. One common requirement when working with Select2 is setting the selected value of the dropdown list programmatically. In this tutorial, we will explore how to set the selected value of a Select2 dropdown list.
Understanding Select2
Before diving into the solution, let’s understand how Select2 works. Select2 can be used with both HTML select elements and hidden input fields. When using a hidden input field, Select2 creates a virtual dropdown list that allows users to search and select options.
Setting Selected Values without AJAX
When not using AJAX to load data, setting the selected value of a Select2 dropdown list is straightforward. You can use the val()
method provided by jQuery to set the value of the underlying select element or input field.
// HTML
<select id="lang">
<option value="php">php</option>
<option value="asp">asp</option>
<option value="java">java</option>
</select>
// JavaScript
$("#lang").select2();
$("#lang").val('asp').trigger('change');
Alternatively, you can use the select2('val')
method provided by Select2:
$("#lang").select2();
$("#lang").select2('val', 'asp');
Setting Selected Values with AJAX
When using AJAX to load data, setting the selected value of a Select2 dropdown list requires more effort. You cannot simply use the val()
method or the select2('val')
method because the options are loaded dynamically via AJAX.
To set the selected value in this case, you need to create an option element with the desired value and text, append it to the underlying select element or input field, and then trigger a change event to update Select2.
// JavaScript
$('#sel')
.empty() // empty select
.append($("<option/>") // add option tag in select
.val("20") // set value for option to post it
.text("nabi")) // set a text for show in select
.val("20") // select option of select2
.trigger("change"); // apply to select2
Alternatively, you can use the select2('data')
method provided by Select2:
$('#sel').select2('data', { id: '20', text: 'nabi' });
Note that when using the select2('data')
method, you need to provide an object with id
and text
properties.
Conclusion
In this tutorial, we explored how to set the selected value of a Select2 dropdown list. We covered both scenarios where data is loaded without AJAX and with AJAX. By following the examples provided in this tutorial, you should be able to set the selected value of your Select2 dropdown lists programmatically.