1
<input type="text"></input>

<script>
var a = document.getElementsByTagName('input')[0];
a.onkeypress = function(evt) {
  this.evt = evt || event;
var b = String.fromCharCode(evt.keyCode);
 while(forEach(evt) {
     alert("You pressed " + b);
   }
};
</script>

This doesn't seems to be working. It should always alert the key when user presses a key. The browser here is Chrome.

1
  • You need to close that script tag. Commented May 30, 2013 at 8:57

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

2

There is no need for a while loop. Simply grab the key in a cross browser compliant manner, find its char equivalent and alert it.

var a = document.getElementsByTagName('input')[0];
a.onkeypress = function(event) {
  //e.which & e.keyCode are for cross browser compliance
  alert(String.fromCharCode(event.keyCode || event.which)); 
};

Working Example http://jsfiddle.net/VZEQe/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.