Jquery:过滤按键输入

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

Jquery: filter input on keypress

javascriptjqueryregexkeypresskeyup

提问by Fernando

I have a text field, which will accept only the following characters:

我有一个文本字段,它只接受以下字符:

Allowed characters: [a-z 0-9 + # - .]

允许的字符:[az 0-9 + # - .]

This is the same filter SOdoes in the 'Tags' field, when you're asking a question. If the user types an invalid character, i want the current text field value to remain unchanged. I tried:

这是相同的过滤器SO确实在“标签”字段,当你问一个问题。如果用户键入无效字符,我希望当前文本字段值保持不变。我试过:

$('#post_tags').keypress(function(event){
    var char = String.fromCharCode(event.which)
    var txt = $(this).val()

    if (! txt.match(/[^A-Za-z0-9+#-\.]/)){
        $(this).val(txt.replace(char, ''));
    }
})

Why it doesn't work? Thanks!

为什么它不起作用?谢谢!

采纳答案by Jerry

/[^A-Za-z0-9+#-\.]/

This negates the match of any one of those characters. To make it match more than one character, you have to use a +in there:

这否定了这些字符中的任何一个的匹配。要使其匹配多个字符,您必须在其中使用 a +

/[^A-Za-z0-9+#-\.]+/
                  ^

And now to match the whole string, you need to add anchors:

现在要匹配整个字符串,您需要添加锚点:

/^[^A-Za-z0-9+#-\.]+$/
 ^                  ^

EDIT: Okay, it seems that the -here is also creating a range from character #to .. In this case, you can either escape it, or put it at the end:

编辑:好的,似乎-这里也在创建从字符#.. 在这种情况下,您可以将其转义,也可以将其放在最后:

/^[^A-Za-z0-9+#\-\.]+$/

/^[^A-Za-z0-9+#\.-]+$/

回答by ExceptionLimeCat

This worked for me:

这对我有用:

$(function(){
    $('#t').keypress(function(e){
        var txt = String.fromCharCode(e.which);
        console.log(txt + ' : ' + e.which);
        if(!txt.match(/[A-Za-z0-9+#.]/)) 
        {
            return false;
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="t" />

回答by SpYk3HH

Alternate Solution

替代解决方案

One thing that might help would be to use the .whichfield instead. Then simply return false when it doesn't fit. I actually have a huge objectfull of .which info for all major browsers. It includes arrays you could borrow from it to create something like:

可能有帮助的一件事是改用该.which字段。然后在不合适时简单地返回 false。我实际上有一个巨大的对象,其中包含所有主要浏览器的 .which 信息。它包括您可以借用它来创建类似以下内容的数组:

var alphaNumericNcontrols = [ 8,9,13,16,17,18,19,20,32,33,34,35,36,37,38,39,40,44,45,46,145,48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,96,97,98,99,100,101,102,103,104,105 ],
    illegal = {
        reg: [ 106,111,191,220 ],
        shift: [ 56,59,188,190,191,220,222 ]
    }

$(document).on("keydown", "input[type=text]", function(e) {
    var eKey = e.which || e.keyCode;
    if (alphaNumericNcontrols.indexOf(eKey) === -1) return false;
    if (illegal.reg.indexOf(eKey) > -1) return false;
    if (e.shiftKey && illegal.shift.indexOf(eKey) > -1) return false;
});

See Working Example Here

请参阅此处的工作示例

Keep in mind my Object is not perfect and there are some updates I probably need to make to it, but i did my best to establish everything from every possible major browser!

请记住,我的对象并不完美,我可能需要对其进行一些更新,但我已尽力从每个可能的主要浏览器中建立所有内容!

回答by Fernando

Thanks everyone.

谢谢大家。

Actually my problem was a little more difficult: filter invalid keys and start a ajax call for valid ones, in 2 different ways: if the user press SPACE/COMMA or while he/her still typing. Here's the code:

实际上我的问题有点困难:过滤无效键并以两种不同的方式开始对有效键的 ajax 调用:如果用户按空格/逗号或他/她仍在打字。这是代码:

$(document).ready(function(){

$('#post_tags').keypress(function(e){
    var txt = String.fromCharCode(e.which);
    console.log(txt + ' : ' + e.which);

    if(txt.match(/^[^A-Za-z0-9+#\-\.]+$/))
    {
          return false;
    }
})

$('#post_tags').keyup(function(event){
      code = event.which
      var token = String.fromCharCode(code)
      var txt = $(this).val()

              //create a new tag, take it out of textfield
      if (code == 32 || code == 188)
      {
        console.log("AJAX new word keyup")

          $.ajax({
            type: 'get',
            url: '/posts/tags_change',
            dataType: "json",
            data: "query=" + $(this).val(),

            success: function(data) {
            console.log(data)
            $('#post_tags').val('')
            },

            error: function(data) {
                alert("Ajax error")
            }
          });
    }
    else
    {
                    //do autocomplete ajax
        console.log("typing:" + txt)
    }

});

})

})

Dont' know if this is 100% right!

不知道这是否100%正确!

回答by Arvy

You don't need to replace the char, only prevent it.

您不需要替换字符,只需防止它。

var char = String.fromCharCode(event.which)
if (!char.match(/^[^A-Za-z0-9+#\.\-]+$/)) event.preventDefault();