1

This is the code. i just want to hide message when i press backspace key, i don't know why it is not going away on backspace other than that it works fine.

    //on keypressed in textbox
    $(".phone").keypress(function (e) {
        if (e.which == 8 ){
            $(".errmsg").hide();
        }
        //if not numeric, then it don't let you type
        if (e.which != 8 && e.which != 43 && e.which != 45  && (e.which < 48 || e.which > 57)) {
           debugger
            //display error message
            $(".errmsg").html("Digits Only").show();
            e.preventDefault();
        } else {
            debugger
            $(".errmsg").hide();
        }
    });

1 Answers1

4

Please use keyup and keydown events to handle this.

//on keypressed in textbox
$(".phone").on('keyup keydown', function(e) {
    if (e.which == 8) {
        console.log('backspace key pressed');
    }

    //if not numeric, then it don't let you type
    if (e.which != 8 && e.which != 43 && e.which != 45 && (e.which < 48 || e.which > 57)) {

        //display error message
        $(".errmsg").html("Digits Only").show();
        e.preventDefault();
    } else {

        $(".errmsg").hide();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

 <input type="text" class="phone" />
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42