HTML DOM
The valueAsNumber property of the HTMLInputElement interface represents the current value of the input element as a number or NaN if converting to a numeric value is not possible.
This property can also be set directly, for example to set a default numeric value based on some condition.
Value
A number that represents the value of the element or NaN if numeric conversion is impossible.
Examples
Retrieving a number value
In this example, the log displays the current value of the input/number input when changed.
HTML
We include an input of type number and an associated label, with a pre container for our output.
<label for="number">Pick a number between 1 and 10:</label>
<input name="number" id="number" min="1" max="10" type="number" />
<pre id="log"></pre>
JavaScript
The <pre> element's HTMLElement.innerText is updated to the current value of the <input> every time a HTMLElement/change_event event is fired.
const logElement = document.getElementById("log");
const inputElement = document.getElementById("number");
inputElement.addEventListener("change", () => {
logElement.innerText = `Number: ${inputElement.valueAsNumber}`;
});
#log {
height: 20px;
padding: 0.5rem;
background-color: #ededed;
}
Results
Retrieving a number value
If you delete the number in the widget, the result is NaN.
Retrieving a date value as a number
This example demonstrates the valueAsNumber property of an <input> with type input/datetime-local.
HTML
We include an <input> of type datetime-local:
<label for="date">Pick a date and time:</label>
<input name="date" id="date" type="datetime-local" />
<pre id="log"></pre>
JavaScript
When no date or time is selected, the empty string resolves to NaN. Each time a selection is made, a HTMLElement/change_event event is fired, updating the <pre> content showing the HTMLInputElement.value of the form control compared to that value as a number.
const logElement = document.getElementById("log");
const inputElement = document.getElementById("date");
logElement.innerText = `Initial value: ${inputElement.valueAsNumber}`;
inputElement.addEventListener("change", () => {
const d = new Date(inputElement.valueAsNumber);
logElement.innerText = `${inputElement.value} resolves to ${inputElement.valueAsNumber}, \nwhich is ${d.toDateString()} at ${d.toTimeString()}`;
});
#log {
height: 20px;
padding: 0.5rem;
background-color: #ededed;
}
Results
Retrieving a date value as a number
Specifications
Browser compatibility
See also
- input
- HTMLInputElement.value
- HTMLInputElement.valueAsDate
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
