HTML DOM Form object


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 −

PropertyDescription
acceptCharsetTo set or return the accept-charset attribute value in a form.
ActionTo set or return the action attribute value of the form
AutocompleteTo set or return the autocomplete attribute value of the form.
EncodingIt is just an alias of enctype.
EnctypeTo set or return the enctype attribute value of the form.
LengthTo return how many elements are there in the form.
MethodTo set or return the method attribute value of the form.
NameTo set or returns the name attribute value of the form.
noValidateTo set or return if the form-data should be validated or not, on being submitted by user.
TargetTo set or return the target attribute value of the form.

Methods

Following are the form object methods −

MethodDescription
reset()To reset a form.
submit()To submit a form.

Example

Let us look at an example of the HTML DOM form object −

Live Demo

<!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>

Updated on: 20-Feb-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements