HTML and CSS Reference
In-Depth Information
needed to convert the value to a floating-point number, you likely used
parseFloat
, but
HTML5 has provided a new solution, the
valueAsNumber
property.
When you read the
valueAsNumber
property of a
number
input type, the property
returns the number as a floating-point number. If you assign a floating-point number to
the
valueAsNumber
property of a
number
input type, the property will convert the
floating-point number to a string-based value.
Using valueAsDate for date and time fields
In the case of date/time fields, there is a property,
valueAsDate
, that works much like
the
valueAsNumber
property. When you use it to retrieve the value of a date-oriented
field, it will return a
Date
object. Similarly, you can use the property to set the value of
the field to a
Date
object.
The
valueAsNumber
property should be available on browsers that support the new
number
input type—but what if the browser doesn't support this and has fallen back to a
regular text input? In this case, you can fall back on the JavaScript
parseFloat
function.
The following statements are equivalent for reading the floating-point value of a field:
value
=
field
.
valueAsNumber
;
//HTML5 version
value
=
parseFloat
(
field
.
value
);
//Fallback version
Similarly, the following statements provide the same result when modifying the floating-
point value of a field:
field
.
valueAsNumber
=
value
;
//HTML5 version
field
.
value
=
value
.
toString
();
//Fallback version
Why use valueAsNumber instead of parseFloat?
At this point, you may be wondering why you'd use
valueAsNumber
at all, when you
can use
parseFloat
instead, and it'll work consistently across all browsers.
value-
AsNumber
offers a more concise way to convert values between string and floating-point.
Also, using
valueAsNumber
over
parseFloat
could lead to a tiny increase in per-
formance, but this is unlikely to be noticeable in most web applications. When the use-