jquery按键在输入文本限制中,我希望它只允许A-Z和空格,但我的代码不允许“Y”和“Z”

jquery keypress in input text restriction, i want it to allow A-Z and white space only but my code won't allow "Y" and "Z"

本文关键字:A-Z 空格 代码 不允许 我的 输入 文本 jquery 我希望      更新时间:2023-09-26

实际上我没有编写这个代码,我只是复制并粘贴它来尝试。

这是代码。

$("#firstname, #lastname").keypress(function(event) {
  var inputValue = event.charCode;
  if (!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) {
    event.preventDefault();
  }
  $('#input').html(inputValue);
});

y 的键码是 121,同样z 键码是 122。因此,如果要将它们包含在范围内,则应将inputValue <= 120更改为 inputValue <= 122 .

但是,您无需为此检查键码。我建议使用正则表达式/[^a-z's]/gi(这是一个否定的字符类,将匹配不a-z或空格的字符 - 不区分大小写(。

您可以简单地将这些字符替换为空字符串并有效地删除它们:

$("#firstname, #lastname").on('input', function(event) {
  this.value = this.value.replace(/[^a-z's]/gi, '');
});

基本示例:

$("#firstname, #lastname").on('input', function(event) {
  this.value = this.value.replace(/[^a-z's]/gi, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="firstname" type="text" />