Using jQuery with forms - part 2 (Core)

Sunday, 1 November 2009

This is the second 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 Core functionality.

jQuery Object Accessors


Applying a function to each of the elements in the form

// Loop over each of the text elements in the form #my_form
 and set their background color to red if they are empty
$("#my_form :text").each(function() {
 if (!$(this).val()) {
  $(this).css('background-color', 'red');


Returns the number of matching elements

// Alerts the number of password elements in the form
alert($("#my_form :password").size());


Returns the element at the specified position

// Returns the third radio element with the name browser in 
the form (count starts from 0)
$("#my_form :radio[name='browser']").eq(2);


Returns the index of a matched element if found (starting from 0) otherwise -1

// Alerts the index of each radio element amongst its siblings

$("#my_form :radio").click(function() {

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