Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
JAVASCRIPT FORMS / CHAPTER 05 / Learn / LESSON 02
Theory. Every field has .value — but it is always a string. Text inputs, number inputs, and selects give their value as text. Read them at the moment of the event (click), not at load — the user has not typed anything yet.
input[type=number].value returns "3", not 3. For math use Number(el.value). select.value is the value of the selected option (not the visible text).
Small examples:
const qty = document.querySelector("#qty"); const n = Number(qty.value); const cat = document.querySelector("#cat").value;
In Code Lab the host fills the fields and clicks the button — you write the listener.
Common mistake: reading value outside the listener; adding "3" + "4" and getting "34"; expecting the visible option text instead of its value.
<input id="title" type="text"><input id="qty" type="number" value="1"><select id="cat"><option value="food">Food</option><option value="fun">Fun</option></select><button id="go" type="button">Show</button><p id="out"></p>value is always a string; use Number for numbers; select.value is the option value.
Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›