Javascript form input type=”number” still returning a string

Quick Solution:

Instead of “value” to get the data, use “valueAsNumber.”

For example:

document.getElementById(“demo”).value;

to

document.getElementById(“demo”).valueAsNumber;

It will convert the input form data, which is in the text format by default, into numbers. When you enter the numbers in your form, the javascript will consider the input as a number.

The type element in the HTML form is always input, even when you enter the numbers. Local browsers translate the HTML form element.

Even though the users are restricted to typing only numbers in the input type numbers, the browser will consider the number as text. Therefore, when you fetch the data using the javascript application, the data is recorded as text.

If you use the javascript operators to run addition or multiplication on the received form data, the result will be combined together and shown on your screen.

Thus, 2 + 2 will always end up 22. Maths formula will not be applied to the numbers. Use “valueAsNumber.” instead of “value” in the javascript statement to convert the text input into numbers.

Leave a Reply