Thursday, August 20, 2009

jQuery removeOptionByValue plugin for dropdown list

I needed to remove an option with a specific value from a select element with JavaScript.
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

4 comments:

  1. var x=document.getElementById("mySelect"); x.remove(x.selectedIndex);

    ReplyDelete
  2. Yes, that is how you can remove an option by it's index.
    But 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()

    ReplyDelete
  3. Damn Niels, you made me improve my code :P
    I 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.

    ReplyDelete
  4. Guitar TOTO TOTO TOTO Guitar TOTO TOTO TOTO TOTO TOTO Guitar
    Guitar 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

    ReplyDelete