I have a page where I need to capture input from a user after they click on a part of the page (a div). Here's my code:
<html>
<body>
<div style="background-color: lightpink" onkeydown="onkeydown1(event)" tabindex="-1">
click me, then press a key
</div>
<script type="text/javascript">
function onkeydown1(event)
{
alert(event.charCode);
}
</script>
</body>
</html>
See it in action: http://jsfiddle.net/WRwBF/
It took me the longest time to get this far because FireFox doesn't by default allow a div to "have focus." Eventually I found out that setting the tabindex for the div allows it to be in focus and the onkeydown event works.
My problem now is that when I click in the div and press a key, the value "0" is returned regardless of what key is pressed. Why would this be happening, and how can I fix it?
I would very much appreciate any guidance you might be able to give!
The charCode property returns the Unicode character code of the key that triggered the onkeypress event. The Unicode character code is the number of a character (e.g. the number "97" represents the letter "a"). Tip: For a list of all Unicode characters, please study our Complete Unicode Reference.
e.keyCode - used to get the number that represents the key on the keyboard. e.charCode - a number that represents the unicode character of the key on keyboard.
Read http://unixpapa.com/js/key.html.
Summary: using the keypress
event is the only way to get reliable information about the character typed. The following will be good enough to get you the character typed in most situations:
var charCode = (typeof event.which == "undefined") ? event.keyCode : event.which;
alert("Character typed: " + String.fromCharCode(charCode));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With