How to remove items from a select box ?
Last Updated :
21 Jun, 2019
An option can be removed from a select box using 2 approaches in jQuery:
Method 1: Removing the option in the box directly
The option to be removed is selected by getting the select box. The value to be removed is specified on the value selector (value=’optionValue’) on the select box. The remove() method is then used to remove this selected option.
Syntax:
$("selectBox option[value='optionValue']").remove()
Example:
<!DOCTYPE html>
< html >
< head >
< title >
Removing an item from a select box
</ title >
</ head >
< body >
< h1 style = "color: green" >
GeeksForGeeks
</ h1 >
< b >Removing an item from a select box</ b >
< p >
Select one from the given options:
< select id = "select1" >
< option value = "free" >
Free
</ option >
< option value = "basic" >
Basic
</ option >
< option value = "premium" >
Premium
</ option >
</ select >
</ p >
< p >Click the button below to
remove one option from the select box.</ p >
< button onclick = "removeOption()" >
Remove option
</ button >
< script src =
</ script >
< script type = "text/javascript" >
function removeOption() {
/* select the option with the
value of basic and remove the option*/
$("#select1 option[value='basic']").remove();
}
</ script >
</ body >
</ html >
|
Output:
- Before clicking the button:
- After clicking the button:
Method 2: Using the find() method
The find() method can be used to find the option in the value with the value selector. This method searches through the descendants of the specified elements in the DOM and creates a new jQuery object from the matching elements.
The select box is first selected and then the find() method is applied with the value selector to find the option. The remove() method is then used to remove this selected option.
Syntax:
$('selectBox').find('[value="basic"]').remove()
Example:
<!DOCTYPE html>
< html >
< head >
< title >
Removing an item from a select box
</ title >
</ head >
< body >
< h1 style = "color: green" >
GeeksForGeeks
</ h1 >
< b >
Removing an item from a select box
</ b >
< p >
Select one from the given options:
< select id = "select1" >
< option value = "free" >
Free
</ option >
< option value = "basic" >
Basic
</ option >
< option value = "premium" >
Premium
</ option >
</ select >
</ p >
< p >
Click the button below to remove
one option from the select box.
</ p >
< button onclick = "removeOption()" >
Remove option
</ button >
< script src =
</ script >
< script type = "text/javascript" >
function removeOption() {
/* select the option with the
value of basic and remove the option*/
$('#select1').find('[value="basic"]').remove();
}
</ script >
</ body >
</ html >
|
Output:
- Before clicking the button:
- After clicking the button:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...