Get form input values in JavaScript
Beginner · 4 min read
Sign-up pages, search boxes, checkout pages: almost every website has a form, and almost every form needs JavaScript to read what the user typed. Maybe you want to check it, maybe you want to send it to a server without reloading the page.
In this tutorial you will read the first name and last name out of a form when it is submitted, and stop the page from reloading. You should know what an HTML form looks like and what a function is. Everything else is explained here.
What happens when a form is submitted
Here is the form for this exercise:
<form id="form1">
<label>First name: <input type="text" name="fname" value="David"></label>
<label>Last name: <input type="text" name="lname" value="Beckham"></label>
<input type="submit" value="Submit">
</form>
When someone presses the Submit button, the browser's default behavior is to send the form's data off and load a new page. That reload throws away everything your JavaScript was doing. So the first job is to say "don't do the default thing, I'll handle it".
Fields, names and values
Each field has a name (like fname) and a value (what is in the box right now). A form element gives you all of its fields in form.elements. You can loop over that list with for...of, just like an array.
Here is the exercise. Have a go first if you want, or keep reading and we will build it step by step.
2 Read the values out of a form
easyA form has a first-name and a last-name input. Read both values when it is submitted, without the page reloading.
Stuck? Three hints, smallest first
- 1.
form.elementsholds the fields, and they can be reached by name. - 2. A submit handler must call
event.preventDefault()or the page reloads and your values are gone. - 3. An input’s
valueproperty and itsvalueattribute stop agreeing once the user types.
Step 1: look at the form's fields
Start by finding the form and listing what is inside it.
const form = document.getElementById('form1');
console.log(form.elements.length); // 3
for (const field of form.elements) {
console.log(field.type); // text, then text, then submit
}
Three fields, but only two of them are data. The third is the Submit button, which counts as a form field too. If you collect every field blindly, the button ends up in your data.
Step 2: collect the values by name
Now build an object where each key is a field's name and each value is what the field holds. Skip the submit button.
const form = document.getElementById('form1');
function getFormValue(theForm) {
const fields = {};
for (const field of theForm.elements) {
if (field.type === 'submit') continue; // a button is not data
fields[field.name] = field.value;
}
return fields;
}
const data = getFormValue(form);
console.log(data.fname); // David
console.log(data.lname); // Beckham
continue jumps straight to the next field, so the button is never added. fields[field.name] = field.value uses the field's name as the key, which means you can add a third input later and this function picks it up with no changes.
Step 3: read the values on submit, without the reload
Listen for the form's submit event. The listener receives an event object, and event.preventDefault() cancels the browser's default action, which here is the reload.
const form = document.getElementById('form1');
function getFormValue(theForm) {
const fields = {};
for (const field of theForm.elements) {
if (field.type === 'submit') continue;
fields[field.name] = field.value;
}
return fields;
}
let captured = null;
form.addEventListener('submit', (event) => {
event.preventDefault(); // stop the reload
captured = getFormValue(event.target);
});
form.dispatchEvent(new Event('submit', { cancelable: true })); // a submit sent from code
console.log(captured.fname, captured.lname); // David Beckham
event.target is the element the event happened on, here the form. Listening on the form, not on the button, is the right choice: a form can also be submitted by pressing Enter inside a text box, and the submit event covers both.
Leave out preventDefault() and try it in a browser. The page flashes, the boxes reset, and your values are gone.
Step 4: read .value, not the value attribute
There is one more trap. The value="David" in the HTML is only the starting value. Once someone types, the value property changes but the attribute does not.
const first = document.querySelector('[name="fname"]');
first.value = 'Ada'; // what typing does
console.log(first.value); // Ada
console.log(first.getAttribute('value')); // David
getAttribute('value') still says David, the value the page was built with. Always read .value to get what the user actually typed.
A shorter way in the browser
Browsers also have FormData, which reads every named field of a form in one go:
form.addEventListener('submit', (event) => {
event.preventDefault();
const data = new FormData(event.target);
console.log(data.get('fname'), data.get('lname'));
});
The live demo on this page uses it. The loop in Step 2 is worth knowing anyway, because it shows exactly which fields count.
The full solution
The panel builds the form, attaches the submit listener and submits it from code. Its checks confirm both names are read, the button is left out, the reload is prevented and typing changes .value but not the attribute. Press Run to see it.
allow-scripts only, so it cannot reach this page.const first = el('input', { type: 'text', name: 'fname', value: 'David' });
const last = el('input', { type: 'text', name: 'lname', value: 'Beckham' });
const submit = el('input', { type: 'submit', value: 'Submit' });
const form = el('form', { id: 'form1' }, [first, last, submit]);
document.body.appendChild(form);
// Reading by name, which is what form.elements is for.
function getFormValue(theForm) {
const fields = {};
for (const field of theForm.elements) {
if (field.type === 'submit') continue; // not data
fields[field.name] = field.value;
}
return fields;
}
let captured = null;
let reloadPrevented = false;
form.addEventListener('submit', (event) => {
event.preventDefault(); // stop the reload
reloadPrevented = event.defaultPrevented;
captured = getFormValue(event.target);
});
console.log('fields found:', form.elements.length);
console.log('initial values:', getFormValue(form));
fire(form, 'submit');
console.log('captured on submit:', captured);
// Once a user types, the property changes and the attribute does not.
first.value = 'Ada';
console.log('property :', first.value);
console.log('attribute:', first.getAttribute('value'), '<- still the original');
Output
12 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 12 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the form has three fields', form.elements.length, 3);
test('both names are read', Object.keys(captured), ['fname', 'lname']);
test('the first name', captured.fname, 'David');
test('the last name', captured.lname, 'Beckham');
test('the submit button is not treated as data', Object.keys(captured).includes(''), false);
test('the reload was prevented', reloadPrevented, true);
test('and the event records it', true, true);
test('typing changes the value property', first.value, 'Ada');
test('but NOT the value attribute', first.getAttribute('value'), 'David');
test('so reading the attribute gives stale data', first.getAttribute('value') === first.value, false);
test('a resubmit picks up the new value', (() => { fire(form, 'submit'); return captured.fname; })(), 'Ada');
test('a field can be found by name', document.querySelector('[name="lname"]').value, 'Beckham');
event.preventDefault() is not optional in a submit handler. Without it the browser submits and reloads, your handler's work is discarded, and the symptom is a page that "flashes and loses everything".
The value/attribute split is the sharper trap. input.value is the live contents; the value attribute is only the initial value. Once anyone types, getAttribute('value') returns what the page was built with, and the assertions above show the two disagreeing. Always read .value.
In a real browser new FormData(form) is shorter than the loop, which is what the live demo uses. The loop is shown here because it makes the type === 'submit' exclusion visible — a submit button is a form element too, and it would otherwise appear in your data.
Common mistakes
- Forgetting
event.preventDefault(). The browser submits and reloads, and the symptom is a page that "flashes and loses everything". - Reading
getAttribute('value'). That is the starting value from the HTML. It never changes when someone types. - Listening for
clickon the button. Pressing Enter in a text box submits the form without clicking. Listen forsubmiton the form.
Try it yourself
- Add an email input with
name="email"to the form. Check thatgetFormValuereturns it without any change to the function. - After reading the values, show "Hello, David Beckham" in a paragraph under the form using
textContent. - Refuse to accept an empty first name: if
captured.fname.trim()is empty, show a message instead of the greeting.