检查文本框值是字符串还是javascript中的数字 [英] Check if a textbox value is a string or a number in javascript

查看:70
本文介绍了检查文本框值是字符串还是javascript中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有以下代码:

<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.

推荐答案

on 输入元素始终一个字符串。它可能是一串数字。

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).

例如,你会让人们告诉你使用 parseInt(myVar)或一元 + + myVar )或 isNaN(myVar)(其中一元 + 的确如此)或数字(myVar)(相同),

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 仅解析开头的字符串 parseInt(345foo) 345

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

parseInt 当然只适用于整数;对于小数部分的数字你想要 parseFloat

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

所有这些都无法理解成千上万的分隔符

All of those will fail to understand thousands separators

所有这些都无法理解不是的小数点分隔符。(例如,许多语言环境是,有时甚至是空格)

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)

+ myVar Number(myVar) isNaN(myVar)等会将空字符串视为 0

+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?

这篇关于检查文本框值是字符串还是javascript中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆