Is there a jquery solution to remove an item from a drop-down list selected by a display text

advertisements

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?


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();