我有这个样本:
代码HTML:
<input type="text" name="firstname" id="firstname" placeholder="John">
CODE JS:
$(document).ready(function() {
$('#firstname').on('input', function() {
var alphaExp = /^[a-zA-Z]+$/;
var key = String.fromCharCode(event.which);
if(alphaExp.test(key)){
alert("it's OK");
}else{
alert("Wrong");
}
});
});
我想检查用户是否输入字母...以及何时显示消息以及是否接收警告是不正确的。
问题是,如果我的网站始终是真的并且消息&#34;错误&#34; (总是)。
这个功能有什么问题? 你可以帮我解决这个问题吗?
提前致谢!
答案 0 :(得分:1)
传递给event
on
的{{1}}没有input
或which
。
使用输入框的值来测试
上的正则表达式
keyCode
&#13;
$(document).ready(function() {
$('#firstname').on('input', function() {
var alphaExp = /^[a-zA-Z]+$/;
var key = this.value;
if (alphaExp.test(key)) {
console.log("it's OK");
} else {
console.log("Wrong");
}
});
});
&#13;
答案 1 :(得分:0)
试试这个:
$(document).ready(function() {
$('#firstname').on('input', function() {
var alphaExp = /^[a-zA-Z]+$/;
console.log(event);
var key = this.value;
});
});
答案 2 :(得分:0)
<强> JS 强>
$(document).ready(function() {
$('#firstname').on('input', function() {
var alphaExp = /^[a-zA-Z]+$/;
// this will check the above regex against the whole string
// in the input box this will catch copy + paste
if(alphaExp.test(this.value)){
alert("it's OK");
}else{
alert("Wrong");
}
});
});