最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Check if a textbox value is a string or a number in javascript - Stack Overflow

programmeradmin2浏览0评论

Basically I 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 textbox, it will always alert string. Is there a way that if you put a number in the textbox it will alert number instead of string? Thank you.

Basically I 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 textbox, it will always alert string. Is there a way that if you put a number in the textbox it will alert number instead of string? Thank you.

Share Improve this question edited May 4, 2015 at 14:27 MeanGreen 3,3055 gold badges41 silver badges69 bronze badges asked May 4, 2015 at 14:19 wobsorianowobsoriano 13.4k25 gold badges103 silver badges177 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 13

value on input elements is always a string. It might be a string of digits.

If you want to know whether that string only contains valid numbers, you have to parse it (and decide what you consider a valid number, and allow for that).

For instance, you'll get people telling you to use parseInt(myVar) or the unary + (+myVar) or isNaN(myVar) (which does what the unary + does) or Number(myVar) (same), but:

  1. parseInt only parses the beginning of the string, parseInt("345foo") is 345

  2. parseInt is, of course, only for whole numbers; you'd want parseFloat for numbers with fractional portions

  3. All of those will fail to understand thousands separators

  4. All of those will fail to understand a decimal separator that isn't . (e.g., in many locales it's , or sometimes even a space)

  5. +myVar and Number(myVar) and isNaN(myVar) and such will treat an empty string as 0

...that kind of thing. So you have to do some prep on the string according to what input you want to accept.

Once you've decide what format(s) to handle, there are a dozen questions with answers here about doing the actual parsing:

  • How do I Convert a String into an Integer in JavaScript? (note that's integer-specific)
  • What's the fastest way to convert String to Number in JavaScript?

is isNaN (literally "is Not a Number"):

var myVar = document.getElementById('txtbox').value;

var myNum = +myVar;//as suggested by T.J. 
if (isNaN(myNum)) {
   alert('string');
} else{
   alert('number');
}
发布评论

评论列表(0)

  1. 暂无评论