-1

I have a grid with some rows of input boxes. Now I want to trigger some code as user is typing some text in the input box. While it does trigger for most of the keys, for some reason, it is not getting trigerred for left/right arrow keys. What could be the issue ?

$("#my_grid tbody").on('input focus keypress', function(e) {
// Not fired for arrow keys (left/right). Not sure why ?
})
copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • This may help you which uses keydown, explaining also how keypress doesn't work in all cases https://stackoverflow.com/questions/5597060/detecting-arrow-key-presses-in-javascript – GetSet Jul 08 '20 at 08:39
  • Try using `keyup`/`keydown` instead. –  Jul 08 '20 at 08:40
  • 1
    Does this answer your question? [Detecting arrow key presses in JavaScript](https://stackoverflow.com/questions/5597060/detecting-arrow-key-presses-in-javascript) –  Jul 08 '20 at 08:46
  • `keypress` gives you the character that was generated, eg `a` or `A` while `keydown` gives you the key that was pressed like `a` or `shift` or `a with shift`. Keys that don't generate characters (shift / cursor) don't generate a keypress event as there's no character to pass to the event. – freedomn-m Jul 08 '20 at 09:23
  • Would you mind accepting my answer as the solution below. If its addresses whats you wanted and solved your issue ? – Always Helping Jul 12 '20 at 04:49

2 Answers2

0

the problem is that arrow keys press are detected on other events like keydown. Check this: Detecting arrow key presses in JavaScript

Radu Rascol
  • 556
  • 6
  • 7
0

Use keydown function as well in your .on and detect which arrow was pressed on input.

I have recreated the example below for you.

Run Snippet below.

$("#my_grid").on('input focus keypress keydown', function(e) {
  if (e.which == 37) {
    alert("left pressed");
  } else if (e.which == 38) {
    alert("up pressed");
  } else if (e.which == 39) {
    alert("right pressed");
  } else if (e.which == 40) {
    alert("down pressed");
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input id="my_grid" />
Always Helping
  • 14,316
  • 4
  • 13
  • 29