The form as a whole

When a field is contained in a <form> element, its DOM element will have a property form linking back to the form's DOM element. The <form> element, in turn, has a property called elements that contains an array-like collection of the fields inside it.

The name attribute of a form field determines the way its value will be identified when the form is submitted. It can also be used as a property name when accessing the form's elements property, which acts both as an array-like object (accessible by number) and a map (accessible by name).

snippet
<form action="example/submit.html">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
<button type="submit">Login</button>
</form>

<script>
var form=document.querySelector("form");
console.log(form.elements[1].type);
//!password
console.log(form.elements.password.type);
//!password
console.log(form.elements.name.form==form);
//!true
</script>

A button with a type attribute of submit will, when pressed, cause the form to be submitted. Pressing Enter when a form field is focused has the same effect.

Submitting a form normally means that the browser navigates to the page indicated by the form's action attribute, using either a GET or a POST request. But before that happens, a "submit" event is fired. This event can be handled by JavaScript, and the handler can prevent the default behavior by calling preventDefault on the event object.

<form action="example/submit.html">
Value: <input type="text"name="value">
<button type="submit">Save</button>
</form>
<script>
var form=document.querySelector("form");
form.addEventListener("submit",function(event){
console.log("Savingvalue",form.elements.value.value);
event.preventDefault();
});
</script>

Intercepting "submit" events in JavaScript has various uses. We can write code to verify that the values the user entered make sense and immediately show an error message instead of submitting the form when they don't. Or we can disable the regular way of submitting the form entirely, as in the previous example, and have our program handle the input, possibly using XMLHttpRequest to send it over to a server without reloading the page.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +