HTMLInputElement: valueAsNumber property
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The valueAsNumber
property of the HTMLInputElement
interface represents the current value of the 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 number input when changed.
HTML
We include an of type
number
and an associated , with a
container for our output.
JavaScript
The element's
innerText
is updated to the current value of the every time a
change
event is fired.
const logElement = document.getElementById("log");
const inputElement = document.getElementById("number");
inputElement.addEventListener("change", () => {
logElement.innerText = `Number: ${inputElement.valueAsNumber}`;
});
Results
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 with type datetime-local.
HTML
We include an of type
datetime-local
:
JavaScript
When no date or time is selected, the empty string resolves to NaN
. Each time a selection is made, a change
event is fired, updating the 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()}`;
});
Results
Specifications
Specification |
---|
HTML # dom-input-valueasnumber-dev |