38

I need to detect the keycode for a custom search box on my website, but the keycode always returns as zero on Chrome for Android (except for backspace, which returns 8). Has anyone else experienced this, and how did you get around it? Our website works on all mobile browsers except Chrome for Android because we can't detect a non-zero keycode or charcode.

I'm running Chrome 27.0.1453.90 on Android 4.1.2 Jelly Bean. The problem can be duplicated with something as simple as:
alert(event.keyCode);

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
barrrrrrrrrooo
  • 381
  • 1
  • 3
  • 6
  • Could you please post what you're currently working with? – Steve P. Jun 17 '13 at 00:53
  • 1
    I'm running Chrome 27.0.1453.90 on Android 4.1.2 Jelly Bean The problem can be duplicated with something as simple as: `alert(event.keycode);` On Chrome for Android, a-z all return 0 for the keycode and backspace returns 8. I can't figure out any way to detect what key is being pressed with this browser. – barrrrrrrrrooo Jun 17 '13 at 01:21
  • 1
    are you checking the keydown or keypress event? If it's keydown, that's very weird - it looks like it's returning the charCode (Which is 0 on keydown) instead of the keyCode... What about checking the keyIdentifier ? – Etai Dec 14 '13 at 16:51
  • Added a JSbin: http://jsbin.com/iLEnilAb/8/edit?html,output – Havvy Dec 18 '13 at 01:45
  • How is this possible? I'm hours into this bug. Firefox mobile handles it perfectly. This was reported on Chromium in 2012: https://bugs.chromium.org/p/chromium/issues/detail?id=118639 – cbdeveloper Apr 16 '20 at 11:32

10 Answers10

20

below solution also work for me. might be useful for others also.

var getKeyCode = function (str) {
    return str.charCodeAt(str.length - 1);
}

document.getElementById("a").onkeyup = function (e) {
    var kCd = e.keyCode || e.which;
    if (kCd == 0 || kCd == 229) { //for android chrome keycode fix
        kCd = getKeyCode(this.value);
    }
    alert(kCd)
}
coder
  • 1,874
  • 2
  • 22
  • 31
  • 5
    It is only last characters keyCode catched. What if I type in the middle of text input or at the start? – Cody Tookode Apr 09 '16 at 01:50
  • 1. Can you give an example like the above where in a page multiple text-box are accepting only numeric value(int). Many many thanks in advance. 2. Is it possible without jQuerry ?? – B.M. May 04 '16 at 10:57
3

I faced this issue and this is how I figured out how to solve the problem.

  • First, you need to enable USB debugging onto your Android phone so you can see the logs of your browser on your desktop machine.
  • Second, refresh your web app on your phone and inside your console on the desktop type "monitorEvents(document)" or whatever element you want to inspect.
  • Do the action you want to inspect on your phone.

And this is how I found that the keydown event was actually fired by a unique event called "textInput" which contains the information inside event.originalEvent.data.

Hope this saves you time and good luck!

Chololoco
  • 3,140
  • 1
  • 21
  • 24
  • this is working as described but sometimes it do not fire unless i loose focus on the input field, but this is the closest solution to my problem, (keycode always returning 0) – George Jan 29 '18 at 08:36
2

The true way to get the keyCode is to use

event.which

This property on event object is standardize the event.keyCode property. You can read about it also in jQuery documentation here or in MDN here

In other way, I have a lot of experience with keyboard events on android devices. Android browser has problems sometimes with keyboard events due to device fragmentation (different ROMs between devices or external keyboard apps). The best way is to try to use all the keyboard events (keydown, keyup and keypress) and compare every result to get the pressed key.

The best way is to use in "input" event and get all the time the last charter. The input event can control like in my answer here.

Community
  • 1
  • 1
g.e.manor
  • 526
  • 6
  • 12
  • 2
    chrome mobile (`event.which`) still behaves weirdly with respect to some keys. for instance, i have found that it is sometimes necessary to send alt+ to get recognized as a plain (outside of a text field) and a lot of special keys like home/end return as 0. – Michael Apr 04 '14 at 19:36
2

We encountered this problem recently on a China made Android phone Meizu MX3, which has a deeply customized OS based on Android 4.4.4.

The default browswer and Chrome work just fine, but for some weird reasons we don't know, event.keyCode, event.charCode and event.which return 0 all the time in some other browsers(such as CM Browser or webview of Wechat app).

We resolved this by checking the last character you input such as 'A' or ' '(space), then we convert it to ascii code using charCodeAt such as "A".charCodeAt(0) which returns 97, which is the actual char code we need.

But we can only determine the char code of visible chars using this strategy, which meets our current need thank god.

Hope you guys can get some inspiration from this.

Johnny Zhao
  • 2,858
  • 2
  • 29
  • 26
2

I have faced the same issue with Android Devices of SonyXperia and HTC. I have developing hybrid application where i am validating Amount text field by reading event.keyCode() of the entered char on keydown event from text field, so that i can allow only numbers and dot(.) char to be entered. I tried but it doesn't worked, returning always 0 in these devices. Later i came with other solution with keyup event and char matching through Regular Expression:

$("#AmountField").keyup(function (e) {

    var regex = /^[0-9\.]$/;
    var str = $(this).val();
    var subStr = str.substr(str.length - 1);
    if(!regex.test(subStr)) {

        if(str.length >0){
            $(this).val(str.substr(0, (str.length - 1)));
        }else{ 
            $(this).val();
        }

    }

});

Hope this can help for the people who facing this issue. Good Luck.

Raghu
  • 174
  • 13
  • While this would work for most cases, it may not work as well if we needed to handle special key presses like "backspace" :( – thisbytes Mar 11 '16 at 00:05
1
<input type="text" id="char" size="15" onblur="showKeyCode()" value="a">
<input type="button" value="Show Key Code" onclick="showKeyCode();">
<script>
function showKeyCode()
{
    var character = document.getElementById ( "char" ).value.substr(this.length - 1);
    var  code = character.charCodeAt();

    var stringall = document.getElementById ( "char" ).value;
    var msg = "The Key Code for the \""+character+"\" character is "+code+".";
    alert(msg);
 }
</script>

For reference

coder
  • 1,874
  • 2
  • 22
  • 31
0

If anybody still digging it.Problem appears on stock Samsung keyboard for android devices.

Instead use onkeyup.

candidJ
  • 4,289
  • 1
  • 22
  • 32
Sergei Panfilov
  • 1,191
  • 9
  • 15
0

change the type of the input to tel : <input type="tel">

this will let you log the keyCode but it doesnt log the backspace, and it might force the keyboard on mobile to only numbers.

George
  • 716
  • 1
  • 12
  • 29
0

So in most Android browser if u use keydown or keyup you wont be able to get the data from key or keyCode or which or code

You can use event.data(Inserted data key) and event.inputType(backspace or del in mobile)

In order to achieve the functionality you need you have to apply condition based on user agent for android mobile

if (navigator.userAgent.match(/Android/i)) {
    node.addEventListener('input', handleInput, false);
  } else {
    node.addEventListener('keydown', handleKeyDown, false);
  }


  const handleKeyDown = event => {
    event.preventDefault();
    if (!event.key) {
      return false;
    }
    genericFunctionHandleThings(event.key, event.code === 'Backspace');
  };

 const handleInput = event => {
    event.preventDefault(); // Here event.preventDefault doesn't stop user from typing
    genericFunctionHandleThings(event.data, event.inputType === 'deleteContentBackward');
    node.value = storedOrProcessedValue;
  };

Here I have used node.value = storedOrProcessedValue because if we want to make some restriction for user typing we need to process and re assign it to the input

You can use this with Input type text,url,email,tel these I have tested rest I need to check

Siddharth Pandey
  • 649
  • 1
  • 9
  • 21
-1

Need to use charCode instead of keyCode

<input type="text" onKeyPress="return funName(this,event)" />

<script language="javascript">
function funName(th,ev)
{   
   alert(ev.charCode);
}
</script>
Atif Mahmood
  • 8,882
  • 2
  • 41
  • 44