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!