How to Add/Remove items from a dropdownlist using JQuery
December 9, 2008 9 Comments
< asp: DropDownList ID="ddlMyCombo" runat="server" ></asp: DropDownList >
In order to clear a dropdownlist items using JQuery:
$('#ddlMyCombo >option').remove();
for more about the JQuery Seletor expressions take a look on my post JQuery Selector Expressions Demystified
What I am doing here is selecting all the option elements that are child of the element with ID “#ddlMyCombo” which is the dropdownlist id and then deleting them. Doing this is gonna clear all elements of the dropdownlist.
So now in order to add items again to the dropdownlist, we will simply append options HTML elements to our test combo
var myCombo= $('#ddlMyCombo');
myCombo.append($('< option > </option>').val(1).html(option1Text));
What I have done here is that I have selected the dropdownlist first just for convenience. It is similar to saying
document.getElementById('ddlMyCombo')
I then start appending HTML option items to my dropdownlist and set the item value and text.
Hi its good piece of work also I’ve done some work with asp.net web service and Jquery.
Neat piece of code. Thanks
Thanks. Great solve. Best regards.
Another simple way:
$(“#myDDL”).removeOption(/./);
Thanks for this, very handy. I’ve been looking for a way to remove an item from a drop down list when the page loads based on a certain condition. I can modify this to get what I want.
Cheers,
Peter
Cool thanks
great, thanks for this!
James
This is remove the first item?
Nice one liner————