Check if textbox value is string or number in javascript

I basically have the following code:

<input type="text" value="123" id="txtbox"> <script> var myVar = document.getElementById('txtbox').value; if (myVar.substring) { alert('string'); } else{ alert('number'); } </script> 

No matter what value you put in the text field, it will always warn string . Is there a way that if you put a number in a text box, it will warn number instead of a string? Thanks.

+6
source share
2 answers

value on input elements is always a string. It can be a string of numbers.

If you want to know if this string contains only valid numbers, you should analyze it (and decide what you consider to be a valid number, and resolve it).

For example, you force people to use parseInt(myVar) or unary + ( +myVar ) or isNaN(myVar) (which does what unary + does), or Number(myVar) (the same) , but :

  • parseInt parses only the beginning of a line, parseInt("345foo") is 345

  • parseInt , of course, is only for integers; you need parseFloat for numbers with fractional parts

  • All of them cannot understand the dividers of thousands.

  • All of them will not be able to understand the decimal separator, which is not . (for example, in many locales it is , or sometimes even a space)

  • +myVar and Number(myVar) and isNaN(myVar) , and such will treat an empty string as 0

... that kind of thing. Therefore, you need to do some preparation in the line according to which input you want to accept.

Once you decide which format to process, there are a dozen questions with answers here about the actual parsing:

+13
source

- isNaN (literally "not a number"):

 var myVar = document.getElementById('txtbox').value; var myNum = +myVar;//as suggested by TJ if (isNaN(myNum)) { alert('string'); } else{ alert('number'); } 
+3
source

Source: https://habr.com/ru/post/986510/


All Articles