To set Select2 to null, you can use the val()
method and pass null
as the argument. This will clear the selected value and display the placeholder text.
Here's how to do it:
$('#mySelect2').val(null).trigger('change');
This code will:
$('#mySelect2').val(null)
: Set the value of the Select2 element with the IDmySelect2
tonull
..trigger('change')
: Trigger thechange
event to update the Select2 element and ensure it reflects the change.
Practical insights:
- This method works for both single-select and multiple-select Select2 elements.
- Ensure that your Select2 configuration includes a placeholder text for when the value is
null
.
Example:
<select id="mySelect2">
<option value="">Select an option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
$(document).ready(function() {
$('#mySelect2').select2();
// Clear the selection
$('#mySelect2').val(null).trigger('change');
});
This code will initialize the Select2 element and then clear its selection, displaying the placeholder text "Select an option".