Working with Forms
Objectives
By the end of this chapter, you should be able to:
- Access a form’s fields with
.elements - Read and set the value of a text input
- Read and set a checkbox’s checked state
- Read the selected value of a dropdown
💡 Why this matters: Forms are how most pages collect information from a user. Before you can respond to a submission (the next module’s job), you need to know how to read what’s actually in one.
Every example in this lesson uses this same HTML:
<form id="signupForm">
<input type="text" name="username" value="jordan">
<input type="checkbox" name="subscribe" checked>
<select name="plan">
<option value="free">Free</option>
<option value="pro" selected>Pro</option>
</select>
</form>
Accessing a Form’s Fields
Every <form> element has an .elements property, giving you access to every field inside it by name.
const form = document.getElementById("signupForm");
const usernameInput = form.elements["username"];
console.log(usernameInput.value);
// jordan
This works for any field with a name attribute, not just text inputs.
Reading and Setting Text Input Values
A text input’s current value is always on .value, as a string.
usernameInput.value = "erin";
console.log(usernameInput.value);
// erin
Setting .value changes what’s shown in the field immediately, exactly as if the user had typed it themselves.
Checkboxes: .checked
A checkbox doesn’t use .value for its on/off state (its .value is a fixed string set in the HTML). Use .checked instead, a boolean.
const checkbox = form.elements["subscribe"];
console.log(checkbox.checked);
// true
checkbox.checked = false;
console.log(checkbox.checked);
// false
Dropdowns: .value
A <select> works like a text input for reading purposes, .value gives you the value of whichever <option> is currently selected.
const select = form.elements["plan"];
console.log(select.value);
// pro
Setting select.value = "free" would select the option with that value, updating what’s shown in the dropdown.
Try It
- Given a form with a text input named
email, select it throughform.elementsand log its.value. - Set that same input’s
.valueto a new email address and confirm the change by logging.valueagain. - Given a checkbox named
terms, log.checked, then set it totrueand log it again. - Given a
<select name="country">with a few<option>elements, log which one is currently selected with.value.
Recap
form.elements["fieldName"]gets you any field in a form by itsnameattribute.- Text inputs and selects use
.valueto read or set their current value. - Checkboxes use
.checked, a boolean, instead of.value.
Next lesson: this module’s exercises, before Events picks up handling what a user actually does with a form (like submitting it).