views:

104

answers:

3

I need to delete an option from a select in certain circumstances.

Basically:

if(mystatement == true)
{
   //remove item with id 'option1' from select of id 'select1'
}

Anyone know the code for me to achieve this?

Many thanks.

+3  A: 

Edit

Since id is unique in the document no need to relate it to the parent select element. You can do simply

$("#option1").remove();
rahul
A: 

jQuery:

$("#option1").remove();

or

$("#select").remove("#option1");

And the classic javascript method:

var option1 = document.getElementById("option1");
document.getElementById("select1").removeChild(option1);
Andy E
Sorry @Andy. I accidently edited your answer.
rahul
`$("#select1")` is unnecessary. `$("#option1").remove()` will suffice since it is matched by `id`.
Marko Dumic
@Marko: I was editing that in as you posted your comment :-) I left the original in as adding IDs to option tags is fairly uncommon.
Andy E
@rahul: no worries :-)
Andy E
Thanks all, the top one worked perfectly. It was so simple I had forgotten!: )
AndyC
A: 

Remove by Value:

$("#select1 option[value=1]").remove();

Remove by Text:

$("#select1 option:contains(Text)").remove();
gnarf