The Form object represents an HTML <form> element.
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:
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:
Collection | Description |
---|---|
elements | Returns a list of all elements in a form |
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 |
Method | Description |
---|---|
reset() | Resets a form, clear the form input |
submit() | Submits a form |
The Form object supports the standard properties and events.