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?
views:
101answers:
2
+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
2010-01-14 12:15:03
Pretty sure you want quotes around yourtext: `'yourtext'`, unless `yourtext` is a variable, which you should probably make clear.
Dominic Rodger
2010-01-14 12:18:58
@Dominic Rodger. Nope it works as is. Tried it with spaces too.
James Wiseman
2010-01-14 12:21:36
is there anyway to do this for as a class selector so i can remove an item from multiple selects at once?
ooo
2010-01-14 14:04:52
@oo: Yes, I have edited the question accordingly
James Wiseman
2010-01-14 14:17:08
+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
2010-01-14 12:16:17
is there anyway to do this as a class selector so it applies to multiple selects with one set of code?
ooo
2010-01-14 14:05:28