HTML DOM Form length Property

HTMLWeb DevelopmentFront End Technology

The HTML DOM Form length property is used for returning the number of elements that are present inside the form. It is a read-only property.

Syntax

Following is the syntax of the Form length property −

ormObject.length

Example

Let us look at an example of the Form length property −

<!DOCTYPE html>
<html>
<head>
<style>
   form{
      border:2px solid blue;
      margin:2px;
      padding:4px;
   }
</style>
<script>
   function getLength() {
      var len=document.getElementById("FORM1").length ;
      document.getElementById("Sample").innerHTML = "Number of elements present inside the form are :"+len;
}
</script>
</head>
<body>
<h1>Form length property example</h1>
<form id="FORM1">
<label>User Name <input type="text" name="usrN"></label> <br>lt;br>
<label>Password <input type="password" name="pass"></label> <br><br>
<select name="Fruit">
<option value="Mango">Mango<option>
<option value="Litchi">Litchi</option>
<option value="Guava">Guava</option>
</select>
</form>
<br>
<p>Get the number of elements present in the above form by clicking the below button</p>
<button onclick="getLength()">get Length</button>
<p id="Sample"></p>
</body>
</html>

Output

This will produce the following output −

On clicking the “get Length” button −

In the above example −

We have first created a form with id=“FORM1” and it contains a input field with type text, another one with type “password”. It also contains a <select> element for making a drop down list. It means the total elements inside the form element are three −

<form id="FORM1">
<label>User Name <input type="text" name="usrN"></label> <br><br>
<label>Password <input type="password" name="pass"></label> <br><br>
<select name="Fruit">
<option value="Mango">Mango<option>
<option value="Litchi">Litchi</option>
<option value="Guava">Guava</option>
</select>
</form>

We then created a button “get Length” that will execute the getLength() method when clicked by the user −

function getLength() {
   var len=document.getElementById("FORM1").length ;
   document.getElementById("Sample").innerHTML = "Number of elements present inside the form are :"+len;
}

The getLength() function gets the <form> element using the getElementById() method of the document object and assigns its length property value to variable len. Since there are 3 elements inside the form element, it returns 3. This value is then displayed in the paragraph with id “Sample” using its innerHTML property and assigning text to it.

function getLength() {
   var len=document.getElementById("FORM1").length ;
   document.getElementById("Sample").innerHTML = "Number of elements present inside the form are :"+len;
}
raja
Published on 19-Aug-2019 11:46:31
Advertisements