HTMLInputElement.valueAsNumber

HTMLInputElement.valueAsNumber

By default, <input> value's are a string type:

<input type="number" id="my-num">
const inputEl = document.querySelector('#my-num');

inputEl.addEventListener('blur', e => {
  const val = e.target.value;
  console.log(typeof val); // "string"
});

But if the expected input is a number or date that we'll later have to do math with, we can easily capture the value as a number type with valueAsNumber:

const inputEl = document.querySelector('#my-num');

inputEl.addEventListener('blur', e => {
  const val = e.target.valueAsNumber;
  console.log(typeof val); // "number"
});

Note that this only works with <input type="number"> and not type="text". No conversion necessary!⚡


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!