Saturday, March 5, 2011

Remove an option dynamically from Drop down or list using javascript and jquery

If there is a requirement to delete an existing option from a select input field in a form dynamically,  that can be a list box or combo, i.e drop down type of select. You can dynamically remove an option from it using java script or jquery using the following code snippet. The id selector is used here, if you wish you can use other selectors also. To remove an option from select, the following java script can be used,

document.getElementById('SELECT_ID').remove(option_index);

the same can be achieved using the following jquery snippet,

$("#SELECT_ID option[value='OPTION_VALUE']").remove();

For eg:- if the html code for the select is like this,

<select id='myselect'>
<option value="I loves Linux">I loves Linux</option>
<option value="I use windows too">I use windows too</option>
<option value="Linux is free software">Linux is free software</option>
<option value="Java script is simple">Java script is simple</option>
</select>

then the java script code to remove the option 'I use windows too' will be,

document.getElementById('myselect').remove(1); //it is 1 because the index start from 0

using jquery,

$("#myselect option[value='I use windows too']").remove();

No comments:

Post a Comment