Javascript Reference - HTML DOM Form length Property








The length property returns the number of elements in a form.

Browser Support

length Yes Yes Yes Yes Yes

Syntax

var v = formObject.length 

Return Value

A Number type of value representing the number of elements in the form.





Example

The following code shows how to get the value of each element in a form.


<!DOCTYPE html>
<html>
<body>
<!--  w w w.j  a  v a 2s  . co m-->
<form id="myForm" action="url">
  First name: <input type="text" name="fname" value="abc"><br>
  <input type="submit" value="Submit">
</form> 
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    var x = document.getElementById("myForm");
    var i = 0;
    for (i = 0; i< x.length; i++) {
        console.log(x.elements[i].value);
    }
}
</script>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to get the number of elements in a form.


<!DOCTYPE html>
<html>
<body>
<!--  ww  w  . j  a v  a 2s . c  om-->
<form id="myForm" action="url">
  First name: <input type="text" name="fname" value="abc"><br>
  <input type="submit" value="Submit">
</form>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {
    var x = document.getElementById("myForm").length;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows: