Forms and Input Values

Course: JavaScript Beginner

Lesson 16: Forms and Input Values

Level

Beginner

Estimated Reading Time

10–15 minutes

Goal

By the end of this lesson, the learner will be able to:

  • Read values from text inputs, selects, checkboxes, and radio buttons
  • Prevent default form submission and handle it with JavaScript
  • Reset a form and programmatically set input values

Frontend Development Context

Forms are how users give information to an application — login credentials, search queries, profile details, billing addresses, contact messages. Reading, validating, and submitting form data without a page reload is one of the most common tasks in frontend development.

JavaScript takes over form handling by intercepting the submit event with preventDefault(), reading the values from each input, doing something useful with them (validating, sending to an API, or updating the UI), and then providing feedback to the user. Understanding the correct way to read each input type is essential — text inputs, checkboxes, selects, and radio buttons each expose their values differently.

Explanation

All form inputs are selected using querySelector or querySelectorAll. Once you have a reference to an input element, you can read its current value.

For text inputs and textareas, the current value is always a string accessible via .value. Even if the user types a number, .value is a string.

For checkboxes, the relevant property is .checked — a boolean that is true when the checkbox is checked and false when it is not. The .value property exists but represents the value attribute in the HTML, not whether the box is checked.

For select elements, .value gives the currently selected option's value. You can also access .selectedIndex or the .options collection if you need more detail.

For radio buttons, you typically select all radios in the group with querySelectorAll, loop over them, and find the one where .checked is true. Its .value is the selected option.

form.reset() resets all form fields to their default values. You can also set input values programmatically by assigning to .value or .checked.

Using new FormData(formElement) is a more advanced way to collect all form field values at once — it handles every input type automatically and is the right tool when sending form data to a server.

Code Example

This example reads multiple input types from a profile settings form:

const form = document.querySelector("#profile-form");

form.addEventListener("submit", function (event) {
  event.preventDefault(); // stop page reload

  const username = document.querySelector("#username").value.trim();
  const bio = document.querySelector("#bio").value.trim();

  const emailNotifications = document.querySelector("#email-notifications").checked;

  const themeSelect = document.querySelector("#theme");
  const selectedTheme = themeSelect.value;

  const roleInputs = document.querySelectorAll('input[name="role"]');
  let selectedRole = "";
  roleInputs.forEach((input) => {
    if (input.checked) selectedRole = input.value;
  });

  console.log({ username, bio, emailNotifications, selectedTheme, selectedRole });
  document.querySelector("#success-msg").textContent = "Profile saved!";
});

Code Explanation

The handler starts with event.preventDefault() to stop the browser from reloading the page on submit. Without this, all the JavaScript that follows would never run.

username and bio use .value.trim().value reads the string from the field and .trim() removes any leading or trailing whitespace the user may have accidentally typed. This two-step pattern is standard for text input reading.

emailNotifications reads the .checked boolean from the checkbox. It is either true or false — not a string.

selectedTheme reads the .value of the select element, which is the value attribute of whichever <option> the user has selected.

The radio button block uses querySelectorAll to get all inputs with the shared name attribute. The forEach loop checks each one's .checked property. Only one radio in a group can be checked at a time, so this finds the selected value.

The result is logged as an object, which formats nicely in the browser console and confirms all values were read correctly before doing anything further with them.

Pattern Highlights

Positive Pattern: Always call event.preventDefault() as the very first line in a form submit handler — if it throws an error, at least the page will not reload and you will see the error in the console.

⚠️ Neutral Note: .value on a text input always returns a string. If you need the input as a number (for example, an age field), convert it with Number() or parseInt() after reading it.

Negative Pattern: Using .innerHTML of a parent to read input values instead of selecting inputs directly — reading the raw DOM markup of a form does not give you the current field values.

Common Mistakes

Mistake 1: Using .value to check whether a checkbox is checked

The .value property of a checkbox is the HTML value attribute — it does not change based on whether the box is checked.

const newsletter = document.querySelector("#newsletter");

// Wrong — .value is always "on" (the default HTML value attribute)
if (newsletter.value === "on") {
  console.log("subscribed"); // always runs whether box is checked or not!
}

// Correct — .checked is the boolean that reflects actual state
if (newsletter.checked) {
  console.log("subscribed");
}

Always use .checked for checkboxes and radio buttons.

Mistake 2: Forgetting to trim text input values

Users often accidentally add spaces at the start or end of inputs. Using .value without .trim() can cause validation or comparison failures.

const email = document.querySelector("#email").value;

if (email === "[email protected]") {
  // Fails if the user typed "[email protected] " (trailing space)
}

// Correct:
const email2 = document.querySelector("#email").value.trim();

Always .trim() text values before comparing or validating them.

Mistake 3: Reading input values before the DOM is ready

If the script runs before the HTML is parsed, querySelector returns null and reading .value on null throws a TypeError.

// At the top of the file, before DOM is loaded:
const email = document.querySelector("#email").value; // TypeError: null

// Correct: read values inside an event handler or after the DOM is ready
form.addEventListener("submit", function () {
  const email = document.querySelector("#email").value;
});

Always read input values inside event handlers or after confirming the element exists.

Quick Recap

  • Text inputs and textareas: read .value (always a string); use .trim() to remove whitespace
  • Checkboxes and radio buttons: read .checked (a boolean), not .value
  • Select elements: read .value to get the selected option's value attribute
  • Always call event.preventDefault() in submit handlers, and convert numeric inputs with Number() or parseInt() before doing math

Ready to test your understanding? Take the quiz to reinforce what you learned.

© 2026 Ant Skillsv.26.07.07-23:01