Javascript 仅允许使用 jQuery 的字母文本框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2980038/
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-08-23 02:46:31  来源:igfitidea点击:

Allow text box only for letters using jQuery?

javascriptjquery

提问by svk

I want to make a text box allow only letters (a-z) using jQuery. Any examples?

我想让一个文本框只允许使用 jQuery 的字母 (az)。有什么例子吗?

回答by dev-null-dweller

<input name="lorem" onkeyup="this.value=this.value.replace(/[^a-z]/g,'');">

And can be the same to onblurfor evil user who like to paste instead of typing ;)

onblur对于喜欢粘贴而不是打字的邪恶用户来说,也可以是一样的;)

[+] Pretty jQuery code:

[+] 漂亮的 jQuery 代码:

<input name="lorem" class="alphaonly">
<script type="text/javascript">
$('.alphaonly').bind('keyup blur',function(){ 
    var node = $(this);
    node.val(node.val().replace(/[^a-z]/g,'') ); }
);
</script>

回答by rybo111

Accepted answer

接受的答案

The accepted answer may be short, but it is seriously flawed (see this fiddle):

接受的答案可能很短,但它存在严重缺陷(请参阅此小提琴):

  • The cursor moves to the end, no matter what key is pressed.
  • Non-letters are displayed momentarily, then disappear.
  • It is problematic on Chrome for Android (see my comment).
  • 无论按下什么键,光标都会移动到末尾。
  • 非字母暂时显示,然后消失。
  • 它在 Android 版 Chrome 上有问题(请参阅我的评论)。

A better way

更好的方法

The following creates an array of key codes (a whitelist). If the key pressed is not in the array, then the input is ignored (see this fiddle):

下面创建了一组键码(白名单)。如果按下的键不在数组中,则忽略输入(请参阅此小提琴):

$(".alpha-only").on("keydown", function(event){
  // Allow controls such as backspace, tab etc.
  var arr = [8,9,16,17,20,35,36,37,38,39,40,45,46];

  // Allow letters
  for(var i = 65; i <= 90; i++){
    arr.push(i);
  }

  // Prevent default if not in array
  if(jQuery.inArray(event.which, arr) === -1){
    event.preventDefault();
  }
});

Note that this allows upper-case and lower-case letters.

请注意,这允许大写和小写字母。

I have included key codes such as backspace, delete and arrow keys. You can create your own whitelist array from this list of key codesto suit your needs.

我已经包含了诸如退格键、删除键和箭头键之类的键码。您可以从此密钥代码列表中创建自己的白名单数组以满足您的需要。

Modify on paste only

仅在粘贴时修改

Of course, the user can still paste non-letters (such as via CTRL+Vor right-click), so we still need to monitor all changes with .on("input"...but replace()only where necessary:

当然,用户仍然可以粘贴非字母(例如通过CTRL+V或右键单击),因此我们仍然需要监视所有更改,.on("input"...replace()仅在必要时使用

$(".alpha-only").on("input", function(){
  var regexp = /[^a-zA-Z]/g;
  if($(this).val().match(regexp)){
    $(this).val( $(this).val().replace(regexp,'') );
  }
});

This means we still have the undesired effect of the cursor jumping to the end, but only when the user pastes non-letters.

这意味着我们仍然有光标跳到最后的不良效果,但只有在用户粘贴非字母时才会出现。

Avoiding autocorrect

避免自动更正

Certain touchscreen keyboards will do everything in their power to autocorrect the user wherever it deems necessary. Surprisingly, this may even include inputs where autocompleteand autocorrectand even spellcheckare off.

某些触摸屏键盘将尽其所能在其认为必要的地方自动更正用户。令人惊讶地,这甚至可以包括输入,其中autocompleteautocorrect,甚至spellcheck是关闭。

To get around this, I would recommend using type="url", since URLs can accept upper and lower case letters but won't be auto-corrected. Then, to get around the browser trying to validate the URL, you must use novalidatein your formtag.

为了解决这个问题,我建议使用type="url",因为 URL 可以接受大写和小写字母,但不会自动更正。然后,要绕过浏览器尝试验证 URL,您必须novalidateform标记中使用。

回答by Anurag

To allow only lower case alphabets, call preventDefaulton the event object if the key code is not in the range 'a'..'z'. Check between 65..90 or 'A'..'Z' too if upper case should be allowed.

要仅允许小写字母,请preventDefault在键代码不在 'a'..'z' 范围内时调用事件对象。如果应该允许大写,也请检查 65..90 或 'A'..'Z' 之间。

Or, alternatively use one of the many input mask pluginsout there.

或者,也可以使用众多输入掩码插件之一。

See example.

参见示例

?$(<selector>).keypress(function(e) {
    if(e.which < 97 /* a */ || e.which > 122 /* z */) {
        e.preventDefault();
    }
});?????

回答by Vijay Lathiya

// allow only  Alphabets A-Z a-z _ and space
$('.alphaonly').bind('keyup blur',function(){ 
    var node = $(this);
    node.val(node.val().replace(/[^A-Za-z_\s]/,'') ); }   // (/[^a-z]/g,''
);
// allow only  Number 0 to 9
$('.numberonly').bind('keyup blur',function(){ 
    var node = $(this);
    node.val(node.val().replace(/[^0-9]/,'') ); }   // (/[^a-z]/g,''
);

回答by Anjan Kant

Demonstrated below to allow only letters [a-z] using Jquery:

下面演示了只允许使用 Jquery 的字母 [az]:

  $(function() {
    $('#txtFirstName').keydown(function(e) {
      if (e.shiftKey || e.ctrlKey || e.altKey) {
        e.preventDefault();
      } else {
        var key = e.keyCode;
        if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
          e.preventDefault();
        }
      }
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input id="txtFirstName" value="">

回答by dn_pdih

  $("#test").keypress(function(event){
        var inputValue = event.charCode;
        //alert(inputValue);
        if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32) || (inputValue==0))){
            event.preventDefault();
        }
    });
  $("#test1").keypress(function(event){
        var inputValue = event.charCode;
        //alert(inputValue);
        if(!((inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
            event.preventDefault();
        }
    });

  $("#test3").keypress(function(event){
        var inputValue = event.charCode;
        //alert(inputValue);
        if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32)||(inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
            event.preventDefault();
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
For letters:<input type="text" id="test">   <br>
<br>
For Numbers: <input type="text" id="test1">
<br>
<br>
For Alphanumeric: <input type="text" id="test3">

回答by Rijo

Supports backspace:

支持退格:

new RegExp("^[a-zA-Z \b]*$");

This option will not check mobile. So you can use a jQuery Mask Pluginand use following code:

此选项不会检查手机。因此,您可以使用jQuery Mask 插件并使用以下代码:

jQuery('.alpha-field, input[name=fname]').mask('Z',{translation:  {'Z': {pattern: /[a-zA-Z ]/, recursive: true}}});

回答by Mayur Khairnar

$("#txtName").keypress(function (e) {

    var key = e.keyCode;
    if ((key >= 48 && key <= 57) || (key >= 33 && key <= 47) || (key >= 58 && key <= 64) || (key >= 91 && key <= 96) || (key >= 123 && key <= 127)) {
        e.preventDefault();
    }
    var text = $(this).val();
    $(this).val(text.replace("  ", " "));

});  

回答by Henry Gabriel González Montejo

Thanks to the first answer.. made this..

感谢第一个答案..做了这个..

<input name="lorem" class="alpha-only">

<script type="text/javascript">
   $(function() 
   {
        $('.alpha-only').bind('keyup input',function()
        {       
            if (this.value.match(/[^a-zA-Z áéíóúáéíóúüü]/g)) 
            {
                this.value = this.value.replace(/[^a-zA-Z áéíóúáéíóúüü]/g, '');
            }
        });
    });
</script>

This has some improvements like letters with accents, and changing "blur" for "input" corrects the Non-letters displayed momentarily, also when you select text with the mouse and dragging is corrected..

这有一些改进,例如带重音的字母,并且更改“输入”的“模糊”可以更正暂时显示的非字母,当您使用鼠标选择文本并更正拖动时也是如此。

回答by Sachin Parse

JQuery function to allow only small and Capital Letters:

JQuery 函数只允许小写和大写字母:

Text Field:

文本域:

<input id="a" type="text" />

JQuery Function:

jQuery 函数:

$('#a').keydown(function (e) {
    if (e.ctrlKey || e.altKey) {
           e.preventDefault();
    } else {
           var key = e.keyCode;
           if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
                e.preventDefault();
           }
    }
});