Looping through form elements using JavaScript
By Amrit Hallan2005-12-09
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.
Tutorial pages:
|
|
|||||||||
You might also want to check these out:
|
Link to This Tutorial Page!

