Clear Items of a DropDownList using jQuery

A user on a forum recently asked a question on how you clear the items in a drop down list using jQuery.

<asp:DropDownList ID="ddlPeople" runat="server">
</
asp:DropDownList>

The answer to the problem is in the jQuery Selector. The person was using the following jQuery to try and clear the items, but it wasn’t working:

$("select[id$=ddlPeople]").remove();

The items weren’t being removed because the jQuery Selector is wrong. What you need to do is tell the Selector to remove all the children (<option> tags). Like this:

$("select[id$=ddlPeople] > option").remove();

“> option” matches all child elements. Because each item in the drop down list is rendered as an <option> tag, you need to clear the child <option> tags in order to clear the items in a drop down list.






5 comments:

Jason BigD said...

why not just $("select[id$=ddlPeople]").empty(); ?

Anonymous said...

there is lot of difference between empty() and remove()

Remove() will completely remove the element and new element will appended in the same place..

empty()- will delete the content but still the space remains.Any new element will be appended after the old content space..

Anonymous said...

Thank you! I found a few jQuery examples that didn't work. Yours is perfect.

Anonymous said...

If a select contains optgroup tags these will remain. If everything has to be removed use $("#ID").children().remove();

If you use jquerymobile make sure you refresh the ui with:
/* check if there is an selectmenu instance */
var instance = $select.data("selectmenu");
if (instance) {
/* force a rebuild of the ui */ $select.selectmenu("refresh", true);
}

Anonymous said...

Thanks..it worked..