You may have written some code like this before:
This is fine and dandy, but there is actually a better way we can be reading the number value.
I’m talking about this part:
That’s right. Since all the way back in the days of IE10 we’ve had a better way to get and set number values:
So a nicer solution to the above could instead look like:
You could likewise query a DOM node and use it as well:
And, importantly, you can write to it as well!
The type of
valuseAsNumber will always be a number. So this means that if there is no current value set for the input, you will get
NaN as the value.
And don’t forget…
NaN before writing it to places that expect actual numbers
But wait, there’s more!
For date inputs, we also get a handy
valueAsDate property as well:
And, as expected, you can write to it as well
valueAsDate, when the input is empty, we simply get
So you can simply check for if the value is truthy
Yeah, this is not a new thing at all. Even if this may be your first time learning about these properties, they’ve existed for many years, even since the dinosaur days of IE 10.
Now that we know how, we actually treat number and date inputs as proper number and date values, using the
valueAsDate properties, respectively.