我们如何限制只写输入字母? JQuery的

时间:2015-12-14 14:31:07

标签: jquery html

我有这个样本:

link

代码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; (总是)。

这个功能有什么问题? 你可以帮我解决这个问题吗?

提前致谢!

3 个答案:

答案 0 :(得分:1)

传递给event on的{​​{1}}没有inputwhich

使用输入框的值来测试

上的正则表达式

&#13;
&#13;
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;
&#13;
&#13;

答案 1 :(得分:0)

试试这个:

 $(document).ready(function() {
  $('#firstname').on('input', function() {
    var alphaExp = /^[a-zA-Z]+$/;
    console.log(event);
    var key = this.value;
  });
});

答案 2 :(得分:0)

jsFiddle

<强> 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");
      }
   });  
});