How can I capture keyboard events from which keys?

I googled and got the following codes on the net. However, when I press the keyboard key, it does not show me a warning window. I want to get which character I clicked in the warning field. How to fix it?

<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>
+5
source share
4 answers

If you want to receive the entered character, you should use an event keypress, not an event keydown. 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));
    }
};
+7
source

try this jquery code

  $("body").keypress(function(e){
        alert(e.which);
    });
+5
source

key code:

charfield.onkeydown=function(evt){
    var keyCode = (evt.which?evt.which:(evt.keyCode?evt.keyCode:0))
    alert(keyCode);
}
+1

I cannot think from head to head about a good situation when you can use the "on some event" method of the DOM element to handle events on this element.

Best practice is to use addEventListener(or attachEventin older versions of Internet Explorer) as follows:

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

If you want to specify also attachEvent:

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

function alertKeyCode(e) {
    alert(e.keyCode);
}
0
source

All Articles