The HTML DOM Form object is associated with the HTML <form> element. We can create and access a form element using the createElement() and getElementById() method of the document object. We can set various properties of the form object and can get them too.
Properties
Following are the Form object properties −
Property | Description |
---|---|
acceptCharset | To set or return the accept-charset attribute value in a form. |
Action | To set or return the action attribute value of the form |
Autocomplete | To set or return the autocomplete attribute value of the form. |
Encoding | It is just an alias of enctype. |
Enctype | To set or return the enctype attribute value of the form. |
Length | To return how many elements are there in the form. |
Method | To set or return the method attribute value of the form. |
Name | To set or returns the name attribute value of the form. |
noValidate | To set or return if the form-data should be validated or not, on being submitted by user. |
Target | To set or return the target attribute value of the form. |
Methods
Following are the form object methods −
Method | Description |
---|---|
reset() | To reset a form. |
submit() | To submit a form. |
Example
Let us look at an example of the HTML DOM form object −
<!DOCTYPE html> <html> <head> <script> function CreateForm() { var f = document.createElement("FORM"); document.body.appendChild(f); var i = document.createElement("INPUT"); i.setAttribute("type", "password"); f.appendChild(i); } </script> </head> <body> <h1>Form object example</h1> <p>Create a FORM element containing an input element by clicking the below button</p> <button onclick="CreateForm()">CREATE</button> <br><br> </body> </html>
This will produce the following output −
On clicking the CREATE button and writing something in the input field −
In the above example −
We have created a button CREATE that will execute the createForm() method on being clicked by the user −
<button onclick="CreateForm()">CREATE</button>
The CreateForm() method creates a <form> element using the createElement() method of the document object and assigns it to variable f. The form element is then appended to the document body using the appendChild() method. We then create an input element using the createElement() method and a type attribute with value “password” for it using the setAttribute() method.
The setAttribute() method creates an attribute if the attribute previously doesn’t exist. Finally using the appendChild() method on the form element and passing the input element as parameter we append the input element as the child of the form element −
<button onclick="CreateForm()">CREATE</button>