Tuesday, May 5, 2009

Iterating Over Form Elements With JQuery

I recently was tasked with making JQuery iterate over the elements of a form. . The form would be specified by name and the script has to loop over all of the input elements. After some Googling and trial-n-error this is the solution I came up with.

$("form[name=foo] :input").each(function(i) {
console.log($(this).attr('id') + " / " + $(this).val());
}

Instead of outputting to the console you'll probably want to do something more interesting with the results.

Trying to explain a JQuery selector string is a bit like trying explain how to improvise a solo in music. But I'll try anyway.

form
This will select all form elements in the DOM.

[name=foo]
This limits the search to only the form with a name attribute with a value of 'foo'.

:input
This selects all of the input elements of the previously selected form. An 'input' element in this case is any form control.

No comments: