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
!
![Animated 3D Flipping Menu with CSS]()
CSS animations aren't just for basic fades or sliding elements anymore -- CSS animations are capable of much more. I've showed you how you can create an exploding logo (applied with JavaScript, but all animation is CSS), an animated Photo Stack, a sweet...
![7 Essential JavaScript Functions]()
I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener
and attachEvent
. Times have changed but there are still a few functions each developer should...
![Duplicate the jQuery Homepage Tooltips Using Dojo]()
The jQuery homepage has a pretty suave tooltip-like effect as seen below:
Here's how to accomplish this same effect using Dojo.
The XHTML
The above HTML was taken directly from the jQuery homepage -- no changes.
The CSS
The above CSS has been slightly modified to match the CSS rules already...
![WebKit-Specific Style: -webkit-appearance]()
I was recently scoping out the horrid source code of the Google homepage when I noticed the "Google Search" and "I'm Feeling Lucky" buttons had a style definition I hadn't seen before: -webkit-appearance. The value assigned to the style was "push-button." They are buttons so that...
Great tip! Is there anything wrong with parseInt / parseFloat, apart from the extra line of code? (you labeled it “BAD”)
Depending on lang, decimal separator can be comma. So,
parseFloat('0,01');
will return0
instead of0.01
.Leaving this here hoping it saves some time I wish I had saved to some other person looking for an answer…
If you’re using this on an html input, maybe with angular… it works great, but you NEED to add the
'type="number"'
to your input or it will keep giving uNaN
no matter what’s in the input box.The reason ?
for some reason that I am not looking up at this time,
valueAsNumber
does NOT work onString
types, but the default type of an html input isString
.Bonjour,
parseFloat(string, 10)
vsNumber(string)
…