JS Bits with Bill
JS Bits with Bill

JS Bits with Bill

HTMLInputElement.valueAsNumber

HTMLInputElement.valueAsNumber

JS Bits with Bill's photo
JS Bits with Bill

Published on Apr 5, 2021

1 min read

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!

 
Share this