The HTML DOM Form name property is associated with the name attribute of the form element. The form name property is used for setting or getting the form name attribute value. The form name property gives the name to the form.
Syntax
Following is the syntax for −
Setting the form name −
formObject.name = name
Here, the name specifies the name of the form.
Example
Let us look at an example of the Form name property −
<!DOCTYPE html> <html> <head> <style> form { border:2px solid blue; margin:2px; padding:4px; } </style> <script> function ChangeName() { document.getElementById("FORM1").name="FORM_2"; document.getElementById("Sample").innerHTML = "The form name is changed from FORM_1 to FORM_2 "; } </script> </head> <body> <h1>Form length property example</h1> <form id="FORM1" method="post" action="/sample_page.php" name="FORM_1"> <label>User Name <input type="text" name="usrN"></label> <br><br> <label>Age <input type="text" name="Age"></label> <br><br> <input type="submit" value="SUBMIT"> </form> <p>Change the name of the form above by clicking the below button</p> <button onclick="ChangeName()">Change Name</button> <p id="Sample"></p> </body> </html>
Output
This will produce the following output −
On clicking the “Change Name” button −
In the above example
We have first created a form that has id=“FORM1”, method=“post”, action=“/sample_page.php” and name attribute value set to “FORM_1”. The form contains two input fields with type text and a submit button to submit the form data to server −
<form id="FORM1" method="post" action="/sample_page.php" name="FORM_1"> <label>User Name <input type="text" name="usrN"></label> <br><br> <label>Age <input type="text" name="Age"></label> <br><br> <input type="submit" value="SUBMIT"> </form>
We have then created a button, “Change Name” that will execute the ChangeName() method when clicked by the user −
<button onclick="ChangeName()">Change Name</button>
The ChangeName() method gets the form element using the document object getElementById() method and changes its name attribute value to “FORM_2”. This change is then reflected in the paragraph with id “Sample” using its innerHTML() property −
function ChangeName() { document.getElementById("FORM1").name="FORM_2"; document.getElementById("Sample").innerHTML = "The form name is changed from FORM_1 to FORM_2 "; }