Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. HTMLInputElement
  4. valueAsNumber

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⁩.

ThevalueAsNumber property of theHTMLInputElement interface represents the current value of the<input> element as a number orNaN 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 orNaN if numeric conversion is impossible.

Examples

Retrieving a number value

In this example, the log displays the current value of thenumber input when changed.

HTML

We include an<input> of typenumber and an associated<label>, with a<pre> container for our output.

html
<label for="number">Pick a number between 1 and 10:</label><input name="number" min="1" max="10" type="number" /><pre></pre>

JavaScript

The<pre> element'sinnerText is updated to the current value of the<input> every time achange event is fired.

js
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

If you delete the number in the widget, the result isNaN.

Retrieving a date value as a number

This example demonstrates thevalueAsNumber property of an<input> with typedatetime-local.

HTML

We include an<input> of typedatetime-local:

html
<label for="date">Pick a date and time:</label><input name="date" type="datetime-local" /><pre></pre>

JavaScript

When no date or time is selected, the empty string resolves toNaN. Each time a selection is made, achange event is fired, updating the<pre> content showing theHTMLInputElement.value of the form control compared to that value as a number.

js
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

Specifications

Specification
HTML
# dom-input-valueasnumber-dev

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp