【发布时间】:2017-07-19 00:05:21
【问题描述】:
我正在处理一个 HTML 页面,但似乎无法弄清楚如何检查用户输入中是否包含整数。我在 for 循环 isNaN 中尝试了 parseInt、userInput.charAt(i)。似乎没有任何效果。
这是我的 HTML
<label for="author" id="author">Favorite Book Author: </label>
<input type="text" name="author" id="authorText">
这是我的 JavaScript
function checkAuthor(){
var userInput = $("authorText").value;
for(var i = 0; i < userInput.length; i++)
{
if(userInput.charAt(i) <= 0 || userInput.charAt(i) > 0)
{
addError("There is a number in 'Favorite Book Author' input");
return false;
}
else
return true;
}
}
我需要查看用户是否输入了任何整数。如果输入是“Mark5”、“Ma5rk”、“5”,我需要它来捕捉那个 5 并显示错误。无论如何,这会起作用吗?我有一种感觉 .charAt 不起作用,因为它将整数识别为字符串,但我尝试对每个单曲进行 parseInt
var x = parseInt(userInput.charAt(i));
在 for 循环中,然后在 if 语句中比较 x。但似乎没有任何效果
addError函数是这样的
function addError(text){
var mylist = window.document.createElement("li");
var myText = window.document.createTextNode(text);
mylist.appendChild(myText);
window.document.getElementByTagName("ul")[0].appendChild(mylist);
}
【问题讨论】:
-
你应该使用正则表达式
-
您在读取输入值时出现拼写错误。使用 $("#authorText").value;
-
这是可能的,但你只关心数字吗?存在其他非字母输入
-
/\d/.test(userInput);检查输入是否包含数字
标签: javascript html error-handling int