1

I'm trying to get the value of the keyPressed in either a keyPress, keydown, or keyUp event. The different solutions here works well on Chrome, FireFox, IE etc. However they fail on android devices.

I tried several solutions inspired from the following SO:

First Solution:

element.keydown(function (e) { 
    var keyCode = e.charCode || e.keyCode || e.which;
    var digit = String.fromCharCode(keyCode);

    // here digit is "å" on android using danish locale
}

KeyUp yields same result. KeyPressed will not fire on chrome on android.

To reproduce i made a plunkr, which shows the behaviour:

https://plnkr.co/BVUfiJrBr0RBPDst9izD/

It works fine on desktop but the keyCode is always 229 on android browsers, regardless of the key pressed.

I reproduced the error on:

  • Samsung Galaxy S6, Android 5.1.1, Browser: Chrome 48.0.2564.95
  • Sony Experia Z2, Android 5.1.1, Browser: Chrome 48.0.2564.95

It did work on:

  • Samsung Galaxy S6, Android 5.1.1, Browser: Firefox
  • Iphone

Trying to reproduce the error indicates a bug in Chrome. Is there a different way around this issue?

Community
  • 1
  • 1
CodeTower
  • 6,293
  • 5
  • 30
  • 54
  • Possible duplicate of [Capture keys typed on android virtual keyboard using javascript](https://stackoverflow.com/questions/30743490/capture-keys-typed-on-android-virtual-keyboard-using-javascript) – reyiyo Oct 10 '17 at 19:01

2 Answers2

0

Have you tried using the input event? Faced a similar problem once and that helped me back in the day with Android 4.4 (Worked in FF, Chrome and Android's native browser).

Made a small example fiddle. Hope this helps!

kano
  • 5,626
  • 3
  • 33
  • 48
0

I just had to solve this myself. In my case, the element is a text input element. On the keyup event (which fires in all browsers), I blur the input. Now whatever was entered is available in the input.val() and the change event fires. So I add a function on the change event on the input that collects what was entered and returns focus to the input. In my case, I only needed to get a single character. I haven't tested this with a situation where someone is typing quickly and the browser has to execute all of this between rapid keystrokes.

My code looks like this:

$('input').on( 'keyup', function(){
    $(this).blur();
});
$('input').on( 'change', function(){
    // my code to do what I want with the value that was entered,
    // which thanks to the blur() I can get from input.val()
    $(this).focus(); // return focus to the input so the user can continue
});

Maybe this will help?