DumpsterDoggy

Articles

Search
Newest Articles
Recent Tutorials
Related Blogs
Get Microsoft Silverlight
Twitter Updates

Bookmark This

jQuery Drop Down Helper

Chris Missal, September 16, 2008

Here is a little JavaScript function I wrote in conjunction with jQuery that I think is pretty handy:

function clear(id) {
    $("#ddl"+id).empty("option")
        .append($("<option />")
        .attr("selected","true").text("Select "+id));
}

This works on naming conventions you'll see. It accepts one string argument and clears the drop down, while subsequently adding a default value.

Edit: I found this useful when I was working with multiple drop downs. Depending on different events I needed to clear their contents. Imagine picking a car year/make/model; once you pick the year, your choices are limited down to the different makes of that year. A user may select 2003, and the Mazda RX-8 would be available in this instance, but not if the user picked 2002. After the selction we would want to go get all the makes available for that year for display, easy enough right? What if the user changes the year again? We would have to clear the makes and repopulate. That's where I found this snippet useful. If you keep naming conventions the same, you can simply call clear("Make") to clear the drop down with an ID equal to "ddlMake" and places one child option with no value and the text of "Select Make". This is useful if you need this functionality in several different places and are able to use consistent naming conventions in the HTML elements.

Filed Under: JavaScript   jQuery