valueAsNumber Reads Numeric Input Values
Read number inputs with valueAsNumber instead of parsing .value by hand; empty or invalid fields yield NaN that Number.isNaN can catch before math.
Code
const input = document.querySelector<HTMLInputElement>("#price");
const form = document.querySelector<HTMLFormElement>("#price-form");
if (!(input && form)) throw new Error("price form markup missing");
form.addEventListener("submit", (event) => {
event.preventDefault();
// number 输入框:valueAsNumber 直接给数值,空值或非法输入是 NaN
const price = input.valueAsNumber;
// 手动解析 .value 的对照路径:两者结果一致
const parsed = Number(input.value);
console.log(`valueAsNumber: ${price}`);
console.log(`Number(value): ${parsed}`);
console.log(`same: ${Object.is(price, parsed)}`);
if (Number.isNaN(price)) {
input.setAttribute("aria-invalid", "true");
console.log("invalid: enter a number");
return;
}
input.removeAttribute("aria-invalid");
console.log(`total with vat: ${(price * 1.2).toFixed(2)}`);
});
Inside the code
The failure path is explicit — Error is raised when the guard condition holds.
Module-level bindings hold the data — input, form — with no function scope in between.
Points of care
- Standard library end to end — paste it in and it runs.
- This is browser-side code —
documentwill not resolve in Node.
Applying it
Output lines are prefixed (valueAsNumber: $, Number(value): $, same: $), making each step’s effect easy to spot.
Statements that matter
if (!(input && form)) throw new Error("price form markup missing");
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- How does the code behave when input is bad?
- The code refuses to continue: `Error` is thrown while the state is still recoverable.
- Does valueAsNumber Reads Numeric Input Values run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.