Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capture keyboard events are from which keys?

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>
like image 805
Manish Basdeo Avatar asked Jun 28 '11 10:06

Manish Basdeo


People also ask

When a key from keyboard is released which event gets generated?

keyup – fires when you release a key on the keyboard. keypress – fires when you press a character keyboard like a , b , or c , not the left arrow key, home, or end keyboard, … The keypress also fires repeatedly while you hold down the key on the keyboard.

What are the events of keyboard?

There are three types of keyboard events: keydown , keypress , and keyup .

How do I display keyboard inputs on-screen?

Go to Start , then select Settings > Accessibility > Keyboard, and turn on the On-Screen Keyboard toggle. A keyboard that can be used to move around the screen and enter text will appear on the screen. The keyboard will remain on the screen until you close it.


2 Answers

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));
    }
};
like image 54
Tim Down Avatar answered Oct 05 '22 02:10

Tim Down


try this jquery code

  $("body").keypress(function(e){
        alert(e.which);
    });
like image 29
Pranay Rana Avatar answered Oct 05 '22 02:10

Pranay Rana