JavaScript Answers

How Deselect All Values with the jQuery Select2 Drop Down?

Spread the love

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="" rel="stylesheet" />
<script src=""></script>

  <select id="select2">
    <option>Some Text</option>
    <option>Other Text</option>

  <select id="select3">
    <option>Some Text</option>
    <option>Other Text</option>
<button id="clear">clear</button>

Then we write:

  placeholder: "select me"

$("#clear").click(() => {
  $("select").each(function() {

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.