Looping through form elements using JavaScript

by: Amrit Hallan

Looping through form elements using JavaScript

You can loop through all the form fields, their names and values using the following JavaScript code:

for(i=0; i<document.FormName.elements.length; i++)
{
document.write("The field name is: " + document.FormName.elements[i].name + " and it’s value is: " + document.FormName.elements[i].value + ".<br />");
}

An example of looping through all the form fields could be checking and unchecking all the check boxes present on a page (checking all the records to delete, or adding all the items to a shopping cart, for instance). First you have the two “Check All” and “Uncheck All” links:

<a href="javascript: void(0);" onclick="javascript: checkall();">Check All</a> / <a href="javascript: void(0);" onclick="javascript: uncheckall();">Uncheck All</a>

Now the code that loops through all the elements, checks whether it’s a checkbox and check or uncheck it if it is a checkbox:

<script language="JavaScript">

function checkall()
{
for(i=0; i<document.FormName.elements.length; i++)
{
if(document.FormName.elements[i].type=="checkbox")
{
document.FormName.elements[i].checked=true;
}
}
}

function uncheckall()
{
for(i=0; i<document.FormName.elements.length; i++)
{
if(document.FormName.elements[i].type=="checkbox")
{
document.FormName.elements[i].checked=false;
}
}
}

</script>

Both the JavaScript functions above loop through the form elements, check their type and check and uncheck them accordingly.



Article published Friday, 9th December 2005
© 2008 NetVisits, Inc. All rights reserved.