Web Development

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.

About the author

Written by Amrit Hallan.

Amrit Hallan is a freelance web developer. You can follow the link below to checkout his website.

If you found this post useful you may also want to check these out:

  1. Restoring Form Field Values
  2. Controlling Checkboxes with JavaScript
  3. Form Required Fields JavaScript Check
  4. Change Form Field Values, On The Fly, with JavaScript
  5. Ensuring Two Form Fields Have Identical Information
  6. JavaScript Form Input Validation and Correction
  • Anonymous

    I was trying to use jQuery to do this and found I couldn’t then check the boxes again. Your article inspired me to this successful code (where ge_enquiries is the id of the form). Thank you sir!

    var formels = document.forms['ge_enquiries'].elements

    var elnum = formels.length;

    for(i=0;i<elnum;i++)
    {
    if(formels[i].type=='checkbox')
    {
    formels[i].checked=false;
    }
    if(formels[i].type=='text')
    {
    formels[i].value='';
    }
    }