DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

HTMLInputElement.valueAsNumber

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

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

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

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"
});
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (1)

Collapse
 
felquis profile image
Felquis Gimenes

Thank you for sharing, It is missing link to the oficial documentation.