Javascript Reference - HTML DOM Form Object








The Form object represents an HTML <form> element.

Example

We can access a <form> element by using getElementById().


<!DOCTYPE html>
<html>
<body>
<form id="myForm" action="url">
  First name: <input type="text" name="fname" value="abc"><br>
  Last name: <input type="text" name="lname" value="def"><br>
  <input type="submit" value="Submit">
</form><!-- www. j a va  2 s . c o m-->

<button onclick="myFunction()">test</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myForm").action;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

We can create a <form> element by using the document.createElement() method.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<!-- w  w w .  j ava  2  s  . co  m-->
<script>
function myFunction() {
    var x = document.createElement("FORM");
    x.setAttribute("id", "myForm");
    document.body.appendChild(x);

    var y = document.createElement("INPUT");
    y.setAttribute("type", "text");
    y.setAttribute("value", "abc");
    document.getElementById("myForm").appendChild(y);
}
</script>

</body>
</html>

The code above is rendered as follows:





Form Object Collections

Collection Description
elements Returns a list of all elements in a form

Form Object Properties

Property Description
acceptCharset Sets or gets the accept-charset attribute in a form
action Sets or gets the action attribute in a form
autocomplete Sets or gets the autocomplete attribute in a form
encoding Alias of enctype
enctype Sets or gets the enctype attribute in a form
length Returns the number of elements in a form
method Sets or gets the method attribute in a form
name Sets or gets the name attribute in a form
noValidate Turn on or off the validation on submission
target Sets or gets the target attribute in a form

Form Object Methods

Method Description
reset() Resets a form, clear the form input
submit() Submits a form

Standard Properties and Events

The Form object supports the standard properties and events.