Assume you have a form allowing users to filter content based on multiple fields, eg. category and author, and each field is displaying the possible values in a drop-down field along with a link attached to a javascript reset action.
<form name="sort-controls" id="sort-controls"> Select by: <select name="category" id="category"> <option value="0">Category</option> <option value="1">Category 1</option> <option value="2">Category 2</option> <option value="3">Category 3</option> </select> <select name="author" id="author"> <option value="0">Author</option> <option value="1">Author 1</option> <option value="2">Author 2</option> <option value="3">Author 3</option> </select> <a href="#" class="reset">Reset</a> </form>
To reset both drop-downs to the first option use the following jQuery code as your reset function.
jQuery("#sort-controls a.reset").click(function(){
jQuery("#sort-controls select").each(function(){
var field = jQuery(this);
field.val( jQuery("option:first", field).val() );
});
return false;
});
Now when someone clicks on the Reset link and your JavaScript function runs, this code will look at each select field that are children of the sort-controls ID and set the value of the select field to the first option‘s value. Test it out by selecting an option for each select field and click the reset link.
Also note the reset class, in the form example it’s attached to an anchor with “#” as the href attribute‘s value. Any anchor’s relying on JavaScript should still link somewhere to allow users with JavaScript disabled to still reset the fields.