Javascript Form How to - Loop through all elements from a form








Question

We would like to know how to loop through all elements from a form.

Answer


<html>
<head>
<script type="text/javascript" language="javascript">
function CheckCheckboxes(){<!--  ww w .  java 2s. c  o  m-->
    var elLength = document.MyForm.elements.length;
    for (i=0; i<elLength; i++)
    {
        var type = MyForm.elements[i].type;
        if (type=="checkbox" && MyForm.elements[i].checked){
            console.log("Form element in position " + i + " is of type checkbox and is checked.");
        }
        else if (type=="checkbox") {
            console.log("Form element in position " + i + " is of type checkbox and is not checked.");
        }
        else {
        }
    }
}
</script>
</head>
<body>
    <form action="" method="POST" name="MyForm">
       Your Name:<input type="text" name="YourName"/>
       Your Gender:
       <input type="radio" name="Gender" value="Male"/>Male<br />
       <input type="radio" name="Gender" value="Female"/>Female<br />

       Tech
       <input type="checkbox" name="XML"/>&nbsp;XML<br />
       <input type="checkbox" name="XSLT"/>&nbsp;XSLT<br />
       <input type="checkbox" name="SVG"/>&nbsp;SVG<br />
       <input type="checkbox" name="XSL-FO"/>&nbsp;XSL-FO<br />
       <input type="checkbox" name="XForms"/>&nbsp;XForms<br />

       Choice
      <select name="FreeGift">
       <option value="Choice1">Choice 1</option>
       <option value="Choice2">Choice 2</option>
       <option value="Choice3">Choice 3</option>
      </select>
      Comments
      <textarea name="Comments" rows="5" cols="50"></textarea>
      <input type="submit" value="Send Form" onclick="CheckCheckboxes()"/>
    </form>
</body>
</html>

The code above is rendered as follows: