Below code works perfect in Chrome, Firefox, on IPhone, and even in third-party browsers on Android. However, when run within the native browser key events for special characters like Å, Ä, and Ö on my Swedish keyboard are simply not triggered.
The example should only allow the user to enter a single character at a time. Works like a charm, unless I in android press keys like Å, Ä or Ö for which I can enter any number of characters.
Here's a jsFiddle for any who wish to try it out: http://jsfiddle.net/x7H6f/. If u don't have special keys like my Swedish ones printed on your keyboard, characters like é (hold E) should do the "trick".
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Key Event test</title>
</head>
<body>
<input type="text" id="a" name="test" />
<script>
document.getElementById("a").onkeypress = function(e) {
e = e || window.event;
var k = e.keyCode || e.which;
this.value = String.fromCharCode(k);
return false;
}
</script>
</body>
</html>
And no, keydown and keyup don't work either. Did I miss something, or is this a bug? It's horribly annoying when developing Swedish Apps in PhoneGap!
Thanks!
EDIT:
As Manor says in his answer, the input
event can be used. Here's a fiddle which demonstrates the differences between the keypress
, input
, and change
events: http://jsfiddle.net/Qxd76/ (use http://jsfiddle.net/Qxd76/show to view the result on a smartphone).
input
event doesn't returnkeyCode
orwhich
orcharCode
.. – Sailmaker