Home > Software design >  Input type number is returning the value as string
Input type number is returning the value as string

Time:03-29

Why is input type number returning the addition value as string but multiplication value in correct way? Any logic behind this, plz enlighten me

CodePudding user response:

<input> tags always have a string value. That's just how it works. If you force the input to be a number field, then you will get a string of digits.

Why? Because this is what the HTML spec states will be the case. The the best answer I can give you.


I got the value from text box and multiplied it and it did it on correct way but when adding numbers like 55 10 it returns 5510 –

This is due to type coercion. This means that sometimes a string is converted to a number for you.

"55"   10 // 5510

This happens because the operator appends one string onto another.

"a"   "b" // "ab"

But when you multiply

"55" * 10 // 550

A string times a string doesn't make any sense, so it assumes you meant to do math and converts it to numbers for you.


When you want to do math from input fields you should convert it to a number first to ensure it does the right thing.

parseFloat("55")   10 // 65

CodePudding user response:

The purpose of the number type is that mobile browsers use this for showing the right keyboards and some browsers use this for validation purposes. For example the email type will show a keyboard with the @ and '.' on the keyboard and number will show a numeric keyboard.

In this case, .value belongs to the DOM API and such API does have types. But let's see how it's defined. The tag is represented by the HTMLInputElement interface and the value property is of type DOMString:

type="number" is a hint to implement client-side validation and appropriate GUI controls but the underlying element will still store strings.

  • Related