Using jQuery with forms - part 3 (Selectors)

Sunday, 1 November 2009

This is the third in a series of tutorials on using jQuery to manipulate forms. In this series I will be looking at parts of the jQuery API reference in detail. In this tutorial I will be looking at forms and jQuery Selectors.



Matches all elements with the given tag name

// Can be used to select the following elements

Basic Filters

:first / :last

Matches the first or last of group of elements

// Selects the first button element in my form
$("#my_form :button:first"); 

// Selects the last password element in my form
$("#my_form :password:last"); 


Filters out elements from a previous group that match the given selector

// Selects all of the input fields 
// that are not hidden

:even / :odd

Matches all elements with an even or odd index

// Hide all the buttons with an even index
$("#my_form :button:even").hide(); 

// Apply the odd class to all text input elements 
// with an odd index
$("#my_form :text:odd").addClass("odd"); 


Select a single element by its index

// Selects the third radio element with the name browser in 
// the form (count starts from 0) and set it to checked
$("#my_form :radio[name='rad']:eq(2)").attr('checked', 'checked');

:lt(index) / :gt(index)

Selects all elements with an index that is either less than or greater than the one specified

// Remove all radio elements with name browser 
// that have an index less than 2
$("#my_form :radio[name='browser']:lt(2)").remove();

Content Filters


Selects all elements that contain the specified text

// Select all labels that have the word detail
$("#my_form label:contains('detail')");


Selects parents that contain the select area

// Matches all fieldsets that contain 
// at least one radio element


The following special selectors are available for forms

// Matches all input, textarea, select and button elements.

// Matches all input elements of type text.

// Matches all input elements of type password.

// Matches all input elements of type radio.

// Matches all input elements of type checkbox.

// Matches all input elements of type submit.

// Matches all input elements of type image.

// Matches all input elements of type reset.

// Matches all button elements and input elements of type button.

// Matches all input elements of type file.

Form Filters

:enabled / :disabled

Selects elements that either have or do not have the disabled attribute set

// Select all the textareas that are disabled and enable them


Matches elements that are checked (typically checkboxes, radio)

// Select the value of the checked radio element with name browser


Matches option that is selected (typically select element options)

// Get the text value of the select element named cheese
$("select[name='cheese'] :selected").text();

If you found this post useful, here are part 1, part 2, and part 4 of this series.
blog comments powered by Disqus