javascript jQuery 不允许在输入字段中输入字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32494905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:22:25  来源:igfitidea点击:

jQuery do not allow alphabets to be entered in input field

javascriptjqueryjquery-events

提问by LearningDeveloper

My requirement is to not allow user to type in any Alphabets. The below code allows 1 character to be entered even though I have provided the e.preventDefault()method on both keydownand keyupmethods.

我的要求是不允许用户输入任何字母。下面的代码允许输入 1 个字符,即使我e.preventDefault()keydownkeyup方法上都提供了方法。

$(function() {
  // Regular Expression to Check for Alphabets.
  var regExp = new RegExp('[a-zA-Z]');

  $('#test').on('keydown keyup', function(e) {

    var value = $(this).val();

    // Do not allow alphabets to be entered.
    if (regExp.test(value)) {
      e.preventDefault();
      return false;
    }

  }); // End of 'keydown keyup' method.

}); // End of 'document ready'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="test" name="test" />

What am I doing wrong? Is there some other way to get this done?

我究竟做错了什么?有没有其他方法可以完成这项工作?

采纳答案by user4642212

Replace

代替

var value = $(this).val();

by

经过

var value = String.fromCharCode(e.which) || e.key;

After all, you need to check which key has been pressed beforeallowing a character to be typed into the field.

毕竟,允许将字符输入到字段中之前,您需要检查按下了哪个键。

Also, make sure the backspace and delete buttons and arrow keys aren't blocked!

另外,请确保退格键和删除按钮以及箭头键没有被阻止!

$(function() {
  var regExp = /[a-z]/i;
  $('#test').on('keydown keyup', function(e) {
    var value = String.fromCharCode(e.which) || e.key;

    // No letters
    if (regExp.test(value)) {
      e.preventDefault();
      return false;
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="test" name="test" />

If your goal is to only accept numbers, dots and commas use this function instead:

如果您的目标是只接受数字、点和逗号,请改用此函数:

$(function() {
  var regExp = /[0-9\.\,]/;
  $('#test').on('keydown keyup', function(e) {
    var value = String.fromCharCode(e.which) || e.key;
    console.log(e);
    // Only numbers, dots and commas
    if (!regExp.test(value)
      && e.which != 188 // ,
      && e.which != 190 // .
      && e.which != 8   // backspace
      && e.which != 46  // delete
      && (e.which < 37  // arrow keys
        || e.which > 40)) {
          e.preventDefault();
          return false;
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="test" name="test" />

回答by MysterX

You need to store input data somewhere and update it each time user inputs allowed character or reset when disabled

您需要将输入数据存储在某处,并在每次用户输入允许的字符时更新它或在禁用时重置

$(function() {
// Regular Expression to Check for Alphabets.
var regExp = new RegExp('[a-zA-Z]'),
    inputVal = '';

$('#test').on('keydown keyup', function(e) {

    var value = $(this).val();

    // Do not allow alphabets to be entered.
    if (regExp.test(value)) {
        $(this).val(inputVal)
    }
    else{ 
        inputVal = value
    }

}); // End of 'keydown keyup' method.

}); // End of 'document ready'

回答by Yevgeniy Afanasyev

Create a function that will mask it out

创建一个将其屏蔽的函数

jsfiddle

提琴手

$.fn.noMask = function(regex) { 
  this.on("keypress", function(e) {
    if (regex.test(String.fromCharCode(e.which))) {
        return false;
    }
  });
}

$("input").noMask ( /[a-zA-Z]/ );

回答by Rifatul Islam Chowdhury

If you are trying for only alphabet with space you can try it:

如果您只尝试使用带空格的字母表,您可以尝试:

$("#test").on("keypress keyup blur",function (event) { 

 $(this).val($(this).val().replace(/[^a-zA-Z ]/, ""));

if (!((event.charCode > 64 && 
    event.charCode < 91) || event.charCode ==32 || (event.charCode > 96 && 
      event.charCode < 123))) {
      event.preventDefault();
    }
 });

回答by rising_Stark

This code will allow only numbers to be accepted for example in a telepone number input field. This is the improvement on the accepted answer.

此代码将只允许接受数字,例如在电话号码输入字段中。这是对已接受答案的改进。

var regExp = /[0-9]/;
      $("#test").on('keydown keyup blur focus', function(e) {

        var value =e.key;
        /*var ascii=value.charCodeAt(0);
        $('textarea').append(ascii);
        $('textarea').append(value);
        console.log(e);*/
        // Only numbers
        if (!regExp.test(value)
          && e.which != 8   // backspace
          && e.which != 46  // delete
          && (e.which < 37  // arrow keys
            || e.which > 40)) {
              e.preventDefault();
              return false;
        }
      });