Forms are where users give your page information. Reading it is the first step.
Text inputs, textareas and selects: value
<input id="name" type="text" value="Maya">
<textarea id="bio">Loves hiking</textarea>
<select id="role">
<option value="dev">Developer</option>
<option value="design" selected>Designer</option>
</select>
<script>
console.log(document.querySelector("#name").value); // → Maya
console.log(document.querySelector("#bio").value); // → Loves hiking
console.log(document.querySelector("#role").value); // → design
</script>
The value of a <select> is the value attribute of the selected <option> (or its text if there is no value attribute).
Everything is a string
Even type="number" fields give you a string. Convert before doing maths, and handle empty input.
<input id="qty" type="number" value="3">
<script>
const input = document.querySelector("#qty");
console.log(typeof input.value); // → string
console.log(input.value + 1); // → 31 (text joined!)
console.log(Number(input.value) + 1); // → 4
console.log(input.valueAsNumber); // → 3 (a ready-made number)
</script>
An empty number field has value "" and valueAsNumber NaN. See Parsing Numbers.
Clean the input
Users add spaces by accident.
const name = nameInput.value.trim();
Reading when something happens
Read values inside the event handler, at the moment you need them, not when the page loads.
<input id="city" placeholder="City">
<button id="go">Show</button>
<p id="out"></p>
<script>
document.querySelector("#go").addEventListener("click", () => {
const city = document.querySelector("#city").value.trim();
document.querySelector("#out").textContent = city ? `You live in ${city}` : "Please type a city";
});
</script>
Finding fields inside a form
A form has an elements collection, indexed by name or id.
<form id="signup">
<input name="email" value="maya@example.com">
<input name="age" type="number" value="28">
</form>
<script>
const form = document.querySelector("#signup");
console.log(form.elements.email.value); // → maya@example.com
console.log(form.elements.age.value); // → 28
</script>
Give every field a name. It is also what FormData and server submissions use (FormData).
Setting values
input.value = ""; // clear
input.value = "New text";
form.reset(); // restore all fields to their defaults
Labels
Every field needs a <label for="id">. It is essential for accessibility and makes clicking the label focus the field. See Accessible Validation.