It's not working because you're calling a function you don't define (forEach
), here:
while(forEach(evt) {
// ^
If you look in the JavaScript console, you'll see an error related to that.
Also, you don't want to assign to an evt
property on this
:
this.evt = evt || event; // <== Don't do this
Just use the argument:
evt = evt || event;
And there's no reason for a loop if you're going to alert every keypress individually.
Also, input
elements don't have closing tags. It should just be:
<input type="text">
or (in XHTML, and optionally in HTML):
<input type="text"/>
not:
<input type="text"></input>
And finally, note that some browsers use which
for the keycode, others use keyCode
. You can use ||
to use whichever the browser supplies:
String.fromCharCode(evt.which || evt.keyCode)
Here's a minimal update: Live Copy | Live Source
<input type="text">
<script>
var a = document.getElementsByTagName('input')[0];
a.onkeypress = function(evt) {
evt = evt || event;
alert("You pressed " + String.fromCharCode(evt.which || evt.keyCode));
};
</script>