Looping through form elements using JavaScript
by Amrit HallanByteswoth.com
Friday, 17th March 2006
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 />");
}
{
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>
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.
Options:
Printer Friendly
Email Friend
About The Author:
Amrit Hallan is a freelance web designer. For all web site development and web promotion needs, you can get in touch with him at amrit@bytesworth.com . For further details, visit http://www.bytesworth.com You can subscribe to his newsletter [BYTESWORTH REACHOUT] on Web Designing Tips & Tricks by sending a blank email at bytesworth-subscribe@topica.com.
Amrit Hallan is a freelance web designer. For all web site development and web promotion needs, you can get in touch with him at amrit@bytesworth.com . For further details, visit http://www.bytesworth.com You can subscribe to his newsletter [BYTESWORTH REACHOUT] on Web Designing Tips & Tricks by sending a blank email at bytesworth-subscribe@topica.com.
