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″ […]

The post Input valueAsNumber appeared first on David Walsh Blog.


This content originally appeared on David Walsh Blog and was authored by David Walsh

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.


This content originally appeared on David Walsh Blog and was authored by David Walsh


Print Share Comment Cite Upload Translate Updates
APA

David Walsh | Sciencx (2022-04-05T10:42:58+00:00) Input valueAsNumber. Retrieved from https://www.scien.cx/2022/04/05/input-valueasnumber/

MLA
" » Input valueAsNumber." David Walsh | Sciencx - Tuesday April 5, 2022, https://www.scien.cx/2022/04/05/input-valueasnumber/
HARVARD
David Walsh | Sciencx Tuesday April 5, 2022 » Input valueAsNumber., viewed ,<https://www.scien.cx/2022/04/05/input-valueasnumber/>
VANCOUVER
David Walsh | Sciencx - » Input valueAsNumber. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/04/05/input-valueasnumber/
CHICAGO
" » Input valueAsNumber." David Walsh | Sciencx - Accessed . https://www.scien.cx/2022/04/05/input-valueasnumber/
IEEE
" » Input valueAsNumber." David Walsh | Sciencx [Online]. Available: https://www.scien.cx/2022/04/05/input-valueasnumber/. [Accessed: ]
rf:citation
» Input valueAsNumber | David Walsh | Sciencx | https://www.scien.cx/2022/04/05/input-valueasnumber/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.