Disallow typing of few of characters e.g.'<', '>' in all input textboxes using jquery

后端 未结 3 634
粉色の甜心
粉色の甜心 2021-01-24 01:58

How do I achieve this:-
When user types character like \'abcd\' and then \'>\'(an invalid character for my application), I wan

相关标签:
3条回答
  • 2021-01-24 02:13

    Example (keypress):

    $(document).ready(function(){
        $('input:text').bind('keypress', function(event){
    
        if(event.which === 62 || event.which === 60)
           return(false);
        });
    });​
    

    Example (keydown):

    $(document).ready(function(){
      $('input:text').bind('keydown', function(event){
        if(event.which === 226)
           return(false);
      });
    });​
    

    Just make use of the preventDefault and stopPropagation functions for events. Those are triggered by returning (false) within an event handler.

    In this example, I just check for the keycode of < and > which is thankfully on the same key. If we hit that code, we just prevent the default behavior.

    Reference: .preventDefault(), .stopPropagation()

    0 讨论(0)
  • 2021-01-24 02:14

    You should catch the 'keyup' and 'blur' events and attach them to a function that bonifies the input: don't forget that the user can paste an invalid sequence of characters.

    So for example

    $('input[type="text"]').keyup(purgeInvalidChars).blur(purgeInvalidChars)
    
    function purgeInvalidChars()
    {
       this.value = this.value.replace(/[<>]/g, ''); 
    } 
    

    surely you will improve the regexp, maybe replacing all characters except the enabled ones.

    Sorry, I can't test my code, so you should take it cum grano salis :-)

    0 讨论(0)
  • 2021-01-24 02:21
    $('#textBox').keyup(function(e){
                var myText = $('#textBox').val(); 
                myText =  myText.replace(">", "");
                myText =  myText.replace("<", "");
                $('#textBox').val(myText);
            });
    

    -- Update --

    keyup instead keypress

    0 讨论(0)
提交回复
热议问题