November 11, 2009

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.



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET and regular presenter at conferences and user groups throughout Australia. Being an ASP.NET Insider, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with JavaScript. He also blogs regularly at DotNetCurry.com. Follow him on twitter @malcolmsheridan

comments

4 Responses to "Clear Items of a DropDownList using jQuery"
  1. Jason BigD said...
    November 21, 2009 2:44 AM

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

  2. Anonymous said...
    March 22, 2010 11:28 AM

    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..

  3. Anonymous said...
    December 14, 2010 12:06 PM

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

  4. Anonymous said...
    December 21, 2010 2:30 AM

    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);
    }

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions