2

I am using knockout and I have a normal HTML input element. I want to handle the press of up arrow, down arrow, left arrow and right arrow for this input using Knockout way, not any other workaround

here is what I tried

<input type="text" data-bind="textInput: $data, event: {keypress: $parent.HandleMove}" />

but the HandleMove function is fired with all keys except up arrow, down arrow, left arrow and right arrow
I think the reason of that, is being those events handled by something else (to make navigation of characters inside the input itself, like going character left, character right and ....)

NOTE I have done a lot of search before putting this question here are the results

this question and this question are not acceptable for me because they handle the event globally using the $(window) jQuery element, and I do not want to do that.

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131

1 Answers1

3

The keypress event is only fired for "character" keys so not for the arrows key.

From MDN:

The keypress event is fired when a key is pressed down and that key normally produces a character value

So you need to use keydown or keyup event to capture the arrow keys:

<input type="text" data-bind="textInput: $data, event: {keydown: $parent.HandleMove}" />

Demo JSFiddle.

nemesv
  • 138,284
  • 16
  • 416
  • 359