Jquery: filter input on keypress

前端 未结 5 755
花落未央
花落未央 2020-12-18 04:45

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

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

This is the same filter SO

5条回答
  •  生来不讨喜
    2020-12-18 05:03

    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:

    $(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!

提交回复
热议问题