Read form controls and typed values
Quick answer
An input element exposes its current value through .value, which is usually a string even when the input type is number. For number inputs, .valueAsNumber gives a number or NaN if conversion is unavailable. Checkboxes use .checked for the current Boolean state. Read the correct property for the control type, and treat empty or invalid input explicitly.
Browser examples
Run each snippet in a fresh browser document. These are static code blocks; ByteMind browser execution is not verified. Storage examples require a test origin.
const i=document.createElement("input");i.type="number";i.value="12";console.log(typeof i.value,i.valueAsNumber);i.value="";console.log(Number.isNaN(i.valueAsNumber));Expected console output:
string 12trueThe string value and numeric value are different representations; empty converts to NaN.
const i=document.createElement("input");i.type="checkbox";i.value="yes";console.log(i.checked,i.value);i.checked=true;console.log(i.checked,i.value);Expected console output:
false yestrue yesToggling checked does not rewrite the submission value.
Common mistake
Do not use Boolean(input.value) to determine a checkbox state. An empty numeric input is not automatically a valid zero.
Practice
Create labeled quantity and checkbox controls; read number and Boolean values separately, including empty quantity.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Read form controls and typed values — Knowledge Check
Apply the concept and predict the browser example behavior.
What type is a number input’s value property?
How should an empty number input be detected with valueAsNumber?
Which property gives a checkbox’s current selected state?
What is the exact console output in Read form controls and typed values example 1?
const i=document.createElement("input");i.type="number";i.value="12";console.log(typeof i.value,i.valueAsNumber);i.value="";console.log(Number.isNaN(i.valueAsNumber));What is the exact console output in Read form controls and typed values example 2?
const i=document.createElement("input");i.type="checkbox";i.value="yes";console.log(i.checked,i.value);i.checked=true;console.log(i.checked,i.value);