11

I will get a Char from keydown event.

In all browsers I can use event.key and it works fine, but in android the result is something else:

event.key: unidentified
event.code: ''
event.which: `229` (for [a-z0-9] is always this number)
window.event.keyCode: `229`

Here is an old stackoverflow post, but it doesn't work any more.

codepen demo for test in android (IOS and PC work fine)

How can i get key code or key string from KeyboardEvent

Adrian
  • 1,558
  • 1
  • 13
  • 31
miladfm
  • 1,508
  • 12
  • 20

2 Answers2

1

i was going trough the same problem in android. i found out that using the input event solved the problem. this event contains the whole string which is actualy typed so if you just one the last character typed just take the last character of the string "event.data"

        document.addEventListener('input',function(event){
        console.log(event)
        let word = event.data === null ? '' : event.data
        input.search(word)

    })
TamoMbobda
  • 11
  • 2
0

Although this question is pretty old, I got here while searching for a similar thing and maybe this can help others.

Assuming you get text in HTML via:

<textarea id="my_input"></textarea>

or:

<input id="my_input"></input>

And assuming you want to get the last char entered in JavaScript, it works if you get the value of the input and slice everything away except the last char:

document.addEventListener('keyup', function(event) {
    val lastchar = document.getElementById('my_input').value.slice(-1);
});

Note: lastchar will also hold special characters like new line.

This works on Android 12 while (as you pointed out) event.key does not.

fr87
  • 1
  • 1
    Thank you for your answers. But I have to work with `keydown` event. And `keyup` is too late because the new char in already in input filed. – miladfm Feb 18 '22 at 11:27