DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

4 2

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.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay