Selecting Options in Select Drop-Downs using jQuery

Tuesday, June 10th, 2008

Say we want to pre-fill out a form with data retrieved from an XML file.  Once we parse the XML, we need to update the form.  If you know the jQuery library, using the val() and attr() methods are trivial for most inputs.  What about select drop-downs?  There’s no easy way to add the “selected” attribute to a drop-down.

As an example let’s say I have a drop-down of names.  I want to have the name “Nick” selected as the default value.  Using jQuery and XPATH, we can do this in a clean way:

$('select#name').find("option[@value=" + name + "]“).attr(”selected”,”selected”);

The first part $('select#name') simply locates the select drop-down that we want (This is done in a fashion similar to CSS selectors).  The next part will find a child that is an option node and has the value of the name specified.  It will then assign the value “selected” to the attribute “selected.”  Simple as that!

Leave a Reply