不允许使用字母值,但允许输入,退格,删除,箭头等

时间:2015-04-14 07:18:26

标签: jquery

我在keypress调用函数,其中不允许使用字母值,但允许使用enter,backspace,delete,arrow等数字字符

function checkIt(s) {
  if (s.match('/[^a-zA-Z0-9 ]/g')) {
     s = s.replace('/[^a-zA-Z0-9 ]/g', '');
  }
}

HTML

<input type="text" onkeyup="return checkIt(this.value)" maxlength="4"   class="input-layout" value="10" name="test[]">
<input type="text" onkeyup="return checkIt(this.value)" maxlength="4"   class="input-layout" value="10" name="test[]">
<input type="text" onkeyup="return checkIt(this.value)" maxlength="4"   class="input-layout" value="10" name="test[]">
<input type="text" onkeyup="return checkIt(this.value)" maxlength="4"   class="input-layout" value="10" name="test[]">

此代码无效。

2 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情

&#13;
&#13;
$('textarea').keyup(function() {
  $(this).val(function(i, v) {
    return v.replace(/[a-z]/gi, '');
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea></textarea>
&#13;
&#13;
&#13;

或者您可以使用 event.keyCode

执行某些操作

&#13;
&#13;
$('textarea').keypress(function(e) {
  if ((e.keyCode < 91 && e.keyCode > 64) || (e.keyCode < 123 && e.keyCode > 96))
    return false;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea></textarea>
&#13;
&#13;
&#13;

或使用您的代码

&#13;
&#13;
function checkIt(s) {
  s.value=s.value.replace(/[a-z]/gi,'');
}
&#13;
<input type="text" onkeyup="checkIt(this)" maxlength="4"   class="input-layout" value="10" name="test[]">
<input type="text" onkeyup="checkIt(this)" maxlength="4"   class="input-layout" value="10" name="test[]">
<input type="text" onkeyup="checkIt(this)" maxlength="4"   class="input-layout" value="10" name="test[]">
<input type="text" onkeyup="checkIt(this)" maxlength="4"   class="input-layout" value="10" name="test[]">
&#13;
&#13;
&#13;

答案 1 :(得分:0)

有几点需要注意:

  1. 正则表达式不应放在引号中
  2. 放入一个插入符表示您不想要它。既然你想要数字而不是字母,你就不能把它们放在一起。
  3. 您的函数应返回值。
  4. 答案已经由其他人提供,但我认为你应该知道这些要点。