JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 13: Forms and ValidationLesson 61 of 150About 40 minutes

Lesson 61: Reading form values

01Opening question

A sign-up form has text boxes, a drop-down, checkboxes and radio buttons. How does JavaScript read what the person chose?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

form.elements gives every named control. Text inputs and selects have value; checkboxes have checked.

const form = document.querySelector("#signup");
console.log(form.elements.name.value);
console.log(form.elements.plan.value);
console.log(form.elements.terms.checked);

03Objective and prerequisites

Learning objective: Read text, number, select, checkbox and radio values, convert them to the right types, and collect a whole form with FormData.

You need: Lesson 60: Building interactive components, Lesson 14: Switch statements and conditional expressions

Skills practised: Forms, Reading form values.

04Explanation

Every form control has a value: input.value for text boxes, select.value for drop-downs. Values are always strings, even in type="number" inputs.

Checkboxes and radio buttons are on or off: read checkbox.checked (true/false). Their value is the label you gave them, not whether they are ticked.

form.elements.name finds a control by its name attribute, which is what the browser uses when the form is sent. For a group of radio buttons with the same name, form.elements.plan.value is the chosen one.

new FormData(form) collects every named, enabled, successful control at once. Object.fromEntries(new FormData(form)) turns it into a plain object.

05Definitions

Form control
An element that collects input, such as input, select, textarea or a button.
value
The current string value of a form control.
checked
A boolean property telling whether a checkbox or radio button is selected.
form.elements
A collection of a form's controls, accessible by name or index.
FormData
An object that collects a form's named values as key/value pairs.

Open the full glossary

06Visual learning object

Form data inspector. Fill in a live form and see each control's value, checked state and the resulting FormData and object, updated as you type.

Loading the interactive object…

Open the full Form data inspector page with its guided experiment.

07Examples

ex-061-01Values are strings Browser page (sandboxed preview)

Even a number input gives a string; convert before calculating.

const qty = document.querySelector("#qty");
const price = document.querySelector("#price");
console.log(typeof qty.value, qty.value + price.value);
console.log(Number(qty.value) * Number(price.value));
console.log(qty.valueAsNumber + price.valueAsNumber);
Sample input
None
Expected output
string 215 30 17
Common mistake
Adding two input values and getting "215" instead of 17.
Try this
Clear the qty value and log valueAsNumber.
Source
examples/ex-061-01-strings-not-numbers.js

ex-061-02Checkboxes, radios and selects Browser page (sandboxed preview)

checked tells you about ticks; value tells you which option.

const prefs = document.querySelector("#prefs");
const { size, gift, colour } = prefs.elements;
console.log(size.value, gift.checked, gift.value, colour.value);
gift.checked = true;
console.log(gift.checked);
Sample input
None
Expected output
M false yes Blue true
Common mistake
Reading checkbox.value to decide whether it is ticked; value stays "yes" either way.
Try this
Select Small from code and print size.value.
Source
examples/ex-061-02-choices.js

ex-061-03Collecting a form with FormData Browser page (sandboxed preview)

FormData reads every named control; unchecked boxes are left out.

const data = new FormData(document.querySelector("#contact"));
const obj = Object.fromEntries(data);
console.log(Object.keys(obj).join(","));
console.log(JSON.stringify(obj.name.trim()), data.has("newsletter"));
Sample input
None
Expected output
name,email "Sam Lee" false
Common mistake
Expecting newsletter: false in the object; unchecked boxes and disabled fields are simply missing.
Try this
Tick the checkbox in the HTML and run again.
Source
examples/ex-061-03-formdata.js

ex-061-04Several checkboxes with one name Browser page (sandboxed preview)

getAll returns every checked value; fromEntries keeps only the last.

const data = new FormData(document.querySelector("#topics"));
console.log(data.getAll("topic"));
console.log(Object.fromEntries(data).topic);
Sample input
None
Expected output
["css", "js"] js
Common mistake
Using Object.fromEntries on a form with repeated names and losing all but the last value.
Try this
Build an object where topic is the full array.
Source
examples/ex-061-04-getall.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

The total is 1020

Convert input values before adding.

const a = document.querySelector("#a").value;
const b = document.querySelector("#b").value;
const total = a + b;
console.log("Total:", total);

Read an order form

Build an object from different controls.

const form = document.querySelector("#order");
function readOrder(form) {
  // TODO: return { product (trimmed), qty (number), ship, gift (boolean) }
}
console.log(JSON.stringify(readOrder(form)));

A complete form reader

Turn any form into an object, keeping repeated names as arrays.

// Write formToObject(form): uses FormData; a key that appears once
// gets its value, a key that appears more than once gets an array.

09Prediction

Commit to an answer first, then run the real code to compare.

// HTML: <input type="checkbox" id="c" value="on-sale">
const c = document.getElementById("c");
console.log(c.value, c.checked);

What is printed?

10Debugging investigation

Everyone is subscribed

People who leave the Subscribe box empty are still added to the mailing list.

const form = document.getElementById("f");
function readSignup(form) {
  const { email, subscribe } = form.elements;
  return { email: email.value, subscribed: Boolean(subscribe.value) };
}
const signup = readSignup(form);
console.log(signup.email, "subscribed:", signup.subscribed);

More cases in the Debugging Detective Laboratory

11Practical scenario

Order forms

An online shop reads quantity, size and gift-wrap choices from the product form, converts quantity to a number, and builds an order object before sending it. Unchecked boxes are handled explicitly so the server always gets true or false.

const raw = { qty: "2", size: "M" };
const order = { qty: Number(raw.qty), size: raw.size, gift: "gift" in raw };
console.log(JSON.stringify(order));

12Knowledge check

1. What type is input.value for <input type="number">?

  • number
  • string
  • bigint
  • It depends on the content

2. Two number inputs hold 4 and 5. What does a.value + b.value give?

  • 9
  • "45"
  • NaN
  • 20

3. How do you tell whether a checkbox is ticked?

  • checkbox.value
  • checkbox.checked
  • checkbox.selected
  • checkbox.on

4. Why is newsletter missing from the object?

const obj = Object.fromEntries(new FormData(form));
console.log(obj.newsletter); // undefined
  • Unchecked checkboxes are not included in FormData
  • FormData ignores checkboxes
  • fromEntries skips booleans
  • The name must be in quotes

5. How do you read the selected radio in a group named plan?

  • form.elements.plan.value
  • form.plan.checked
  • document.querySelector("[name=plan]").value
  • form.elements.plan[0].value

6. Several checkboxes share name="tag". Which reads all checked values?

  • Object.fromEntries(new FormData(form)).tag
  • new FormData(form).getAll("tag")
  • form.elements.tag.value
  • form.tag.checked

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • The total is 1020: Prints Total: 30; total is a number
  • Read an order form: Prints the order; Follows changes
  • A complete form reader: Prints the object; One checked value stays a string

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-13-forms-and-validation/lesson-061-reading-form-values/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • Form values are strings; convert numbers on read.
  • Checkboxes and radios report checked; value is their label.
  • form.elements finds controls by name.
  • FormData collects a whole form; unchecked and disabled fields are left out.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation reading form values
Context: I am learning reading form values in JavaScript.
Task: Explain how to read text, number, select, checkbox and radio values, and FormData.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction reading form values drill
Context: I have practised reading form values.
Task: Give me six short form-reading programs and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging reading form values bug
Context: My total of two input fields shows 1020 instead of 30.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation reading form values practice
Context: I finished the reading form values exercises.
Task: Create three exercises that read forms into objects with exact expected output.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review reading form values review
Context: Here is my code that uses reading form values.
Task: Review my form-reading code for string/number mistakes and missing checkbox handling.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.