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
var x=document.getElementById("mySelect"); x.remove(x.selectedIndex);
ReplyDeleteYes, that is how you can remove an option by it's index.
ReplyDeleteBut my code is used to remove an option by its value.
And in your case (removing the selected option) i'd use:
$("#mySelect :selected").remove()
Damn Niels, you made me improve my code :P
ReplyDeleteI changed the name of the function to make it more clear what it does.
Also shortened the code by using the itemindex to remove the option, instead of selecting it and then remove it.
Guitar TOTO TOTO TOTO Guitar TOTO TOTO TOTO TOTO TOTO Guitar
ReplyDeleteGuitar TOTO TOTO TOTO TOTO titanium sheets TOTO TOTO TOTO TOTO TOTO TOTO sunscreen with titanium dioxide TOTO TOTO TOTO TOTO TOTO TOTO TOTO TOTO TOTO TOTO dental implants TOTO TOTO TOTO TOTO TOTO titanium septum jewelry TOTO TOTO TOTO TOTO TOTO titanium hair straightener TOTO TOTO TOTO