views:

101

answers:

2

I see a number of examples of removing an item from a select dropdown by the items value ( such as this question ) but is there a way to remove an item from a select dropdown if all I know is the display text?

+7  A: 

Try this:

$("#Select>option:contains(yourtext)").remove();

Tested it locally and it works. The exact snippet of code relevant to me was:

<select id="FundManager1" class="FundManagerSelect">
    <option>Fund Manager 1</option>
    <option>Fund Manager 2</option>
    <option>Fund Manager 3</option>
</select>

Then the jQuery:

$(document).ready(function(){
    alert($("#FundManager1>option").length);  //alerts '3'
    $("#FundManager1>option:contains(1)").remove();
    alert($("#FundManager1>option").length);  //alerts '2'
});

You could always put it in a function:

function RemoveOption(SelectId, TextVal) {
    $("#" + SelectId + ">option:contains(" + TextVal + ")").remove();
}

RemoveOption("FundManager1", "1");

Further Edit for Class Selector Question:

For class selector, replace the '#' with a '.' as you would expect:

$(".YourSelectClass>option:contains(yourtext)").remove();

And as this is just a select, you can speed it up by combining with an element selector:

$("select.YourSelectClass>option:contains(yourtext)").remove();
James Wiseman
Pretty sure you want quotes around yourtext: `'yourtext'`, unless `yourtext` is a variable, which you should probably make clear.
Dominic Rodger
@Dominic Rodger. Nope it works as is. Tried it with spaces too.
James Wiseman
is there anyway to do this for as a class selector so i can remove an item from multiple selects at once?
ooo
@oo: Yes, I have edited the question accordingly
James Wiseman
+3  A: 

I suppose you could iterate over them:

$('select option').each(function()
{
    if ($(this).text() == 'something')
    {
        $(this).remove();
    }
});

Edit: James Wisman's answer is more concise, but this might be easier if the option has awkward characters in it that would otherwise interfere with the selector syntax.

Will Vousden
+1 - Agreed. I've not encoutered too many of these however :-)
James Wiseman
is there anyway to do this as a class selector so it applies to multiple selects with one set of code?
ooo