Showing posts with label options. Show all posts
Showing posts with label options. Show all posts

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