Search code examples
javascriptjqueryeventskeypresskeycode

How do I target the enter key event?


I have the following code that works on all keys except enter, shift etc.

$(document).ready(function(){
$('input[name="tmp_post_tag"]').keypress(function(evt){
    alert("hello");
 });
});

Why won't it work on enter? which is what I want it to do. ive tried evt.char, evt.keyCode evt.which but nothing works.


Solution

  • You need to use KeyDown() event, it will fire on all special keys including enter, alt, shift etc...

    Check this code:

    $(document).ready(function(){
    $('input[name="tmp_post_tag"]').keydown(function(evt){
        console.log('Key pressed : ' + evt.keyCode)
     });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input type="input" name="tmp_post_tag" placeholder="press key here" />