Categories
JavaScript Answers

How to Clear a Drop Down List with JavaScript ?

Spread the love

Sometimes, we want to clear a drop-down list with JavaScript.

In this article, we’ll look at how to clear a drop-down list with JavaScript.

Clear a Drop Down List with JavaScript

To clear a drop-down list with JavaScript, we can use the empty or html method.

For instance, if we have the following dropdown and submit button:

<select>
  <option value='0' disabled selected>Select Value</option>
  <option value='1'>Value 1</option>
  <option value='2'>Value 2</option>
</select>

<input type="submit" value="click me" />

Then we can clear the dropdown with we click on the submit button with jQuery by writing:

$('input').on('click', () => {
  $('select').empty();
});

We add a click handler to the input element with on .

Then in the click handler, we call empty on the select dropdown to empty its entries.

We can do the same thing by calling html on the select dropdown with an empty string:

$('input').on('click', () => {
  $('select').html("");
});

The select dropdown will also be emptied once the button is clicked.

Conclusion

To clear a drop-down list with JavaScript, we can use the empty or html method.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *