JavaScript

Getting the value of an input element as a number without parseInt

Advertisements

Every once in a while, you come across something and you think, how did I not know this earlier? valueAsNumber is that thing for me. Whenever we need the value of an HTMLInputElement, we go to e.target.value. But getting the value of an input element as a number can be done without parseInt or parsing it.

HTMLInputElement.valueAsNumber is an attribute that returns a numeric value of the input field and it returns NaN if the value cannot be converted.

/*
 Assuming an <input type="number" value="3.14" />
*/

console.log(input.valueAsNumber) // 3.14
JavaScript

Some things to note:

  • This only works for inputs with type="number"
  • This can also be used as a setter. So input.valueAsNumber = 45 is valid too.
  • There also is a HTMLInputElement.valueAsDate to get the date from an input with type="date"
  • And there is a setter for date inputs too: input.valueAsNumber = new Date()
Saransh Kataria

Born in Delhi, India, Saransh Kataria is the brain behind Wisdom Geek. Currently, Saransh is a software developer at a reputed firm in Austin, and he likes playing with new technologies to explore different possibilities. He holds an engineering degree in Computer Science. He also shares his passion for sharing knowledge as the community lead at Facebook Developer Circle Delhi, NCR which is a developer community in Delhi, India.

Share
Published by
Saransh Kataria
Tags: javascript

Recent Posts

Fixing cookies are blocked for a website with shields down on Brave

I recently switched completely to the Brave browser and have set ad blocking to aggressive…

4 months ago

Generating a QR code using Node.js

I was preparing a slide deck for a hackathon and decided to put in a…

5 months ago

How to clear the global npx cache

I have been using npx a lot lately, especially whenever I want to use a…

5 months ago

Copy/Pasting output from the terminal

Manually copy-pasting the output of a terminal command with a mouse/trackpad feels tedious. It is…

6 months ago

How To Get The Hash of A File In Node.js

While working on a project, I wanted to do an integrity check of a file…

7 months ago

Native popover API in HTML

Popovers have been a problem that was typically solved by using a third-party solution. But…

7 months ago
Advertisements