To deselect all values with the jQuery Select2 drop down, we can call the val
and trigger
methods on the Select2 drop downs.
For instance, if we have 2 select elements:
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<div>
<select id="select2">
<option></option>
<option>Some Text</option>
<option>Other Text</option>
</select>
<select id="select3">
<option></option>
<option>Some Text</option>
<option>Other Text</option>
</select>
</div>
<button id="clear">clear</button>
Then we write:
$('select').select2({
placeholder: "select me"
});
$("#clear").click(() => {
$("select").each(function() {
$(this).val(null).trigger('change');
});
});
to select all drop downs with $('select')
.
Then we call select2
to convert them both to Select2 drop downs.
We call it with an object with the placeholder
property set to set the placeholder of the drop down.
Next, we add a click event handler to the clear button with the $("#clear").click
method.
We call it with a callback that calls each
on all the select elements.
In the click event handler callback, we call each
with a callback that calls $(this).val(null).trigger('change');
to set the value
attribute of each drop down to null
.
Then we call trigger
to trigger the 'change'
event on it.