Reputation: 196589
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?
Upvotes: 2
Views: 525
Reputation: 30500
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();
Upvotes: 8
Reputation: 33368
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.
Upvotes: 4