Input value is a string instead of a number

Check out HTMLInputElement.valueAsNumber:

The value of the element, interpreted as one of the following in order:

  1. a time value
  2. a number
  3. null if conversion is not possible
var testInput = document.getElementById("test-input");

function handleInput(e){
  var value = this.valueAsNumber;
  console.log("type: %s, value: %o", typeof value, value);  
}

testInput.addEventListener("input", handleInput);
  
handleInput.call(testInput);
<input type="number" id="test-input" type="number" value=5>

This will return NaN for non-numerics or non-finite numbers.

Leave a Comment