Remove an option from a drop-down list with JavaScript/jQuery
This post will discuss how to remove a given option from a dropdown list in JavaScript and jQuery.
1. Using jQuery
To remove an option from a dropdown list, you can use jQuery’s .remove() method. The .remove() method will remove the specified elements out of the DOM.
Using jQuery’s attribute selector, you can use any of the following methods to find the corresponding <option> element:
|
1 2 3 4 5 6 7 8 9 |
$("select option[value=cat]") $("select option").filter("[value=cat]") $("select").children("option").filter("[value=cat]") $("select").children("option[value=cat]") $('select').find('option[value=cat]') |
Here’s a complete example.
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $("#pets option[value=cat]").remove(); }) }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 |
<label for="pets">Choose your pets:</label> <select id="pets"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="rabbit">Rabbit</option> <option value="parrot">Parrot</option> </select> <button id="submit">Remove Cat</button> |
2. Using JavaScript
In plain JavaScript, you can get the corresponding option with the querySelector() method and call the JavaScript’s remove() method upon it.
JS
|
1 2 3 |
document.getElementById('submit').onclick = function() { document.querySelector('#pets option[value=cat]').remove(); } |
HTML
|
1 2 3 4 5 6 7 8 9 10 |
<label for="pets">Choose your pets:</label> <select id="pets"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="rabbit">Rabbit</option> <option value="parrot">Parrot</option> </select> <button id="submit">Remove Cat</button> |
That’s all about removing an option from a drop-down list in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)