Javascript 检查文本框值是数字还是字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6466709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:54:00  来源:igfitidea点击:

Check whether a textbox value is numeric or string

javascript

提问by Romi

Possible Duplicate:
Is there a (built-in) way in JavaScript to check if a string is a valid number?

可能的重复:
JavaScript 中是否有(内置)方法来检查字符串是否为有效数字?

i want to check whether a textbox contains a numeric value or a string using javascript i used this.

我想使用javascript检查文本框是否包含数值或字符串,我使用了它。

var query=getquerystring()
    if(isNaN(query))

        {
           alert("query is a string");
        }
        else{
           alert("query is numeric");

        }

where getquerystring() is a function as

其中 getquerystring() 是一个函数

function getquerystring() {
            var query=document.getElementById("queryString").value;

            return  query;
         }

but when i enter a number 1234 in textbox still getting query is a string. please tell me what is wrong in my code, and suggest me some solution.

但是当我在文本框中输入数字 1234 时,查询仍然是一个字符串。请告诉我我的代码有什么问题,并建议我一些解决方案。

回答by Aleks G

Update:Looking back at my own answer, I realise the problem with it. You can't compare with NaN, you need to use isNaNfunction:

更新:回顾我自己的答案,我意识到它的问题。您无法与 比较NaN,您需要使用isNaN功能:

var query=getquerystring();
if(isNaN(parseFloat(query))
{
   alert("query is a string");
}
else{
   alert("query is numeric");
}

Or, alternatively, you can use regex pattern matching to see if the string matches what it should.

或者,您也可以使用正则表达式模式匹配来查看字符串是否与其应该匹配。