0

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.

Theo E
  • 77
  • 2
  • 11
  • check `evt.keyCode==13` – Bhushan Kawadkar Oct 08 '18 at 12:15
  • I've tried keyCode. It does not work. This right now alerts me hello on ALL keys except for a few like enter and shift. – Theo E Oct 08 '18 at 12:16
  • 1
    I'm not sure exactly what is going on, but from reading the documentation at https://api.jquery.com/keypress/ it seems that `.keypress` is temperamental at best, and you're better off using the `keyup` and/or `keydown` events. – Robin Zigmond Oct 08 '18 at 12:17
  • What browser? That code seems to work in Chrome (including Enter and Shift) – Magnum Oct 08 '18 at 12:19
  • for `keypress` you should use `evt.which == 13`. for `keyup` or `keydown` use `evt.keyCode == 13` – Calvin Nunes Oct 08 '18 at 12:20
  • Either use `keydown` or `keyup`, since keypress might not support all the keys. After that, enter's keycode is **13**. – briosheje Oct 08 '18 at 12:24
  • keydown is working on the alert! Thanks make this an answer so I can vote it best answer! – Theo E Oct 08 '18 at 12:24

2 Answers2

2

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" />
saAction
  • 2,035
  • 1
  • 13
  • 18
  • Check out this example to get more understanding about key events https://howtodoinjava.com/scripting/jquery/jquery-difference-between-keypress-and-keydown-events/ – saAction Oct 08 '18 at 12:25
1

Try this code. the 13 represent the enter key.

$(document).ready(function(){
  $('input[name="tmp_post_tag"]').keypress(function(evt){
    if(evt.which == 13) {
        alert("hello");
    }
  });
});
Mel
  • 858
  • 8
  • 15