It seems that jQuery lacks something like a removeOptionByValue() method.
I tried to use a selector to remove one option, like this: $("#mySelect option[@value=ToBeRemoved]").remove() but that resulted in an error.
So i wrote a little plugin for it.
This is the example HTML:
<select id="ddlTest">
<option value="">- Please choose -</option>
<option value="first">First option</option>
<option value="second">Second option</option>
<option value="third">Third option</option>
</select>
<input id="btnTest" value="Test" type="button">
We would like to remove the option with value "first" when the button is clicked.
This is the javascript i wrote:
(function($) {
$.fn.removeOptionByValue = function(optionValue) {
if ($(this).is("select")) {
var itemIndex = -1;
var dropdownId = $(this).attr("id");
$("#" + dropdownId + " option").each(function() {
itemIndex++;
if ($(this).val() == optionValue) {
$("#" + dropdownId)[0].remove(itemIndex);
}
});
}
}
})(jQuery);
// Test if it works
$("#btnTest").click(function() {
$("#ddlTest").removeOption("first");
});
Download the solution as jQuery plugin here: jquery.removeoptionbyvalue.js
/Ruud
