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

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay