8

I googled and got the following codes on the Net.However, when I press a keyboard key,it is not displaying me an alert box. I want to get which character I have pressed in the alert box. How do I fix this?

<script type="text/javascript">

var charfield=document.getElementById("char")
charfield.onkeydown=function(e){
var e=window.event || e;
alert(e.keyCode);
}

</script>
</head>

<body id="char">

</body>
</html>
Supreeth
  • 27
  • 7
Manish Basdeo
  • 6,139
  • 22
  • 68
  • 102
  • Maybe it will be helpful: http://stackoverflow.com/questions/302122/jquery-event-keypress-which-key-was-pressed – Kamil Jun 28 '11 at 10:19

4 Answers4

9

If you want to get the character typed, you must use the keypress event rather than the keydown event. Something like the following:

var charfield = document.getElementById("char");
charfield.onkeypress = function(e) {
    e = e || window.event;
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
    if (charCode > 0) {
        alert("Typed character: " + String.fromCharCode(charCode));
    }
};
Tim Down
  • 318,141
  • 75
  • 454
  • 536
5

try this jquery code

  $("body").keypress(function(e){
        alert(e.which);
    });
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
1

I can't off the top of my head think of a good situation in which to use the "on some event" method of a DOM element to deal with events on that element.

The best practice is to use addEventListener (or attachEvent in older versions of Internet Explorer) like so:

charfield.addEventListener('keydown', function (e) { alert(e.keyCode); }, false);

If you want to account for attachEvent as well:

(function (useListen) {
    if (useListen) {
        charfield.addEventListener('keydown', alertKeyCode, false);
    } else {
        charfield.attachEvent('onkeydown', alertKeyCode);
    }
})(charfield.addEventListener);

function alertKeyCode(e) {
    alert(e.keyCode);
}
natlee75
  • 5,097
  • 3
  • 34
  • 39
1

You'll get the appropriate key code:

charfield.onkeydown=function(evt){
    var keyCode = (evt.which?evt.which:(evt.keyCode?evt.keyCode:0))
    alert(keyCode);
}
Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
K6t
  • 1,821
  • 1
  • 13
  • 21