Remove selected option from drop-down list with jQuery
This post will discuss how to remove the selected option from the dropdown list with jQuery.
With jQuery, you can use the .remove() method to takes elements out of the DOM. To get the selected item from a dropdown, you can use the :selected property and call remove() on the matched element.
JS
|
1 2 3 4 5 6 |
$(document).ready(function() { $('#submit').click(function() { // get the selected option and remove it from the DOM $('#pets option:selected').remove(); }); }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 |
<label for="pets">Choose your pets:</label> <select name="pets" 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 Selected</button> |
There are numerous ways to get the selected option of the select element with the :selected property:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$("select option:selected").remove(); $("select :selected").remove(); $(":selected", $("select")).remove(); $("select option").filter(":selected").remove(); $("select").children("option").filter(":selected").remove(); $("select").children("option:selected").remove(); $("select").find("option:selected").remove(); |
Another solution is to use the eq() selector. As of jQuery 3.4, the :eq pseudo-class is deprecated and should not be used.
JS
|
1 2 3 4 5 6 7 8 9 |
$(document).ready(function() { $('#submit').click(function() { // get the selected index var index = $('#pets')[0].selectedIndex; // remove the selected index from the DOM $(`#pets option:eq(${index})`).remove(); }) }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 |
<label for="pets">Choose your pets:</label> <select name="pets" 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 Selected</button> |
That’s all about removing the selected option from the drop-down list with 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 :)