Search code examples
javascriptjquerykeypressonkeypress

JQuery keypress special buttons issue


I am working about press the key of insert on the my page , but i have any error about keycode of insert.

$(document).on('keypress', function(e) {
     var code = e.keyCode || e.which;
     console.log(code);
     if(code===45){
          alert("Insert Clicked");
     }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

this is my code . When i clicked some key it work fine , but when i press insert,tab,del,backspace,shift it doesn't work. There is any mistake ? I didn't find any mistake.


Solution

  • You can use keydown with e.preventDefault();:

    $(document).on('keydown', function(e) {
       var code = e.keyCode || e.which;
       console.log(code);
       if(code == 45) {
           e.preventDefault(); 
           alert("Insert Clicked");
       }
    });