Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event.charCode always returning 0

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!

like image 569
Nate Avatar asked Jun 23 '12 23:06

Nate


People also ask

What is event charCode?

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.

What is keyCode and charCode?

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.


1 Answers

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));
like image 62
Tim Down Avatar answered Sep 20 '22 18:09

Tim Down