Input valueAsNumber

Every once in a while I learn about a JavaScript property that I wish I had known about years earlier — valueAsNumber is one of them. The valueAsNumber provides the value of an input[type=number] as a Number type, instead of the traditional string representation when you get the value:

 /*  Assuming an <input type="number" value="1.234" /> */  // BAD: Get the value and convert the number input.value // "1.234" const numberValue = parseFloat(input.value, 10);  // GOOD: Use valueAsNumber input.valueAsNumber // 1.234 

This property allows us to avoid parseInt/parseFloat, but one gotcha with valueAsNumber is that it will return NaN if the input is empty.

Thank you to Steve Sewell for making me aware of valueAsNumber!

The post Input valueAsNumber appeared first on David Walsh Blog.

David Walsh Blog

Posted in: JavaScript

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.