About
This article shows you how to retrieve the data of a form with Javascript
Note that only succesful controls are send on submit.
Method
Elements
You don't need to submit a form to get the values
- Every form object has a elements property that stores all elements:
- enclosed in the form element
- or attached to this form via the form id input attribute
- Every input element has a value attribute
Demo
- The HTML form
<form id="demo">
<input name="user" type="text" />
<input id="ageid" name="age" type="number" value="10" />
</form>
- The Javascript
let form = document.getElementById("demo");
const user = form.elements.user.value;
console.log("User: "+user +" (empty string)");
console.log("Age element index via name: "+form.elements['age'].value);
console.log("Age direct notation via name: "+form.age.value);
console.log("Age direct notation via id: "+form.ageid.value);
- Output:
Submit Event
From the submit event, you can get the following value
- event.submitter.value - the submitter value (ie the submit button)
- event.target.elements - holds the elements and their values
- event.target - the form element
You can:
- select input element via one of the two identifier
- and read the value attribute.
Example with the name attribute.
<form onsubmit="handleSubmit(event); return false;">
<input name="user" type="text" value="Foo" />
<input id="ageid" name="age" type="number" value="10" />
<button type="submit">Get this values !</button>
</form>
handleSubmit = (event) => {
let form = event.target;
console.log("User: "+form.elements.user.value);
console.log("Age element index via name: "+form.elements['age'].value);
console.log("Age direct notation via name: "+form.age.value);
console.log("Age direct notation via id: "+form.ageid.value);
}
FormData
A FormData object is a javascript runtime object of the data of a forms.
It provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method.
For example and more, see its dedicated page: How to use FormData and send multipart-data in the Browser (Web API )?