Tuesday, June 3, 2008

Javascript to Find all form elements

Find all form elements with Javascript DOM

Here's a quick way of finding all the form elements on a given page using the DOM-Friendly getElementsByTagName function. Because it works on the Document Object Model, it'll work on any node in the document. That means you can find the form elements within a given form, fieldset, div or any element on the page. That gives it an advantage over the boring old document.forms array, but it does mean you'll need a DOM-Compatible browser, so no Netscape 3 for you. It might be a nice addition to your unobtrusive javascript arsenal.

The Code:

function getAllFormElements( parent_node ) {
if( parent_node == undefined ) {
parent_node = document;
}
var out = new Array();
formInputs = parent_node.getElementsByTagName("input");
for (var i = 0; i < formInputs.length; i++)
out.push( formInputs.item(i) );
formInputs = parent_node.getElementsByTagName("textarea");
for (var i = 0; i < formInputs.length; i++)
out.push( formInputs.item(i) );
formInputs = parent_node.getElementsByTagName("select");
for (var i = 0; i < formInputs.length; i++)
out.push( formInputs.item(i) );
formInputs = parent_node.getElementsByTagName("button");
for (var i = 0; i < formInputs.length; i++)
out.push( formInputs.item(i) );
return out;
}

The Explanation

Just call it without parameters to get all the form elements on the current page, or pass it a DOM node to find only elements that are descendants of that node. Easy as that.

The function calls getElementsByTagName 4 times so that we get all of the different form element tags. It pushes the results of those calls onto an array. getElementsByTagName returns an HTMLCollection not an array, so pushing all the elements onto the array lets us do even more with the results.

Moreinfo : visit : http://ronandowling.com/2006/05/31/find-all-form-elements-with-javascript-dom/

No comments:

Post a Comment