CodingNic

The DOM

Working with Forms

The DOM 20 min read

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:

text
<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.

javascript
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.

javascript
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.

javascript
const checkbox = form.elements["subscribe"];
console.log(checkbox.checked);
// true

checkbox.checked = false;
console.log(checkbox.checked);
// false

A <select> works like a text input for reading purposes, .value gives you the value of whichever <option> is currently selected.

javascript
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

  1. Given a form with a text input named email, select it through form.elements and log its .value.
  2. Set that same input’s .value to a new email address and confirm the change by logging .value again.
  3. Given a checkbox named terms, log .checked, then set it to true and log it again.
  4. 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 its name attribute.
  • Text inputs and selects use .value to 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).