Remove option element JQuery by clicking the button

Posted on

This is an article which is written to specify and to describe on how to remove option element using JQuery script and it is triggered by clicking the button. Below is the actual snippet code of HTML web-page which is extracted only the part of select HTML element and the button which is used to click and remove the option element exist inside the select HTML element.

First of all, the option element is generated by using a JQuery. To generate the option elements, JQuery can be useful to add it. By defining an array variable which defines the value and attribute of the option element, all the option elements can be inserted to the select HTML element. To see how to add option elements, the following article titled ‘Add select option JQuery from Array Variable’ can be used as a reference in this link.

<select id="list_selection">
</select>
<input type="submit" id="remove_selection_btn" value="Submit"></input>

So, how can an option element be removed from its parent element, the select HTML element ?. It can be easily done by detecting the selected option element or by detecting an event triggered such as a button which is being clicked. Below is the additional script which is declared as part of the JQuery script executed in the same web-page.

 $('#remove_selection_btn').click(function(e){
       $("#list_selection option:selected").remove();
 })

As it can be seen, it will try to search a clicked event from an HTML element with the id of ‘remove_selection_btn’. From the previous snippet code relates with HTML element, it can be understandable that the HTML element with the id of ‘remove_selection_btn’ is a button type HTML element.

<input type="submit" id="remove_selection_btn" value="Submit"></input>

So, if a click event is triggered on an HTML element with the id of ‘remove_selection_btn’, remove directly an HTML element called element which is in the state of selected which is exist in an HTML element with the id of ‘list_selection’. It can be seen in the following line of snippet code :

$("#list_selection option:selected").remove();

One thought on “Remove option element JQuery by clicking the button

Leave a Reply