elepil
asked on
JavaScript's String.fromCharCode() not returning keydown characters accurately, is there another function?
I have a keydown event and I need to convert the event's event.keyCode to its character equivalent. I'm using String.fromCharCode(), but it returns a '3' when I press a '#'.
Is there another function I can use that would convert event.keyCode values to their character equivalents accurately? Thanks in advance.
Here is the code snippet:
Is there another function I can use that would convert event.keyCode values to their character equivalents accurately? Thanks in advance.
Here is the code snippet:
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . "/_includes/init.php";
require_once ROOT . "/_includes/_db/DB.php";
require_once ROOT . "/_includes/dao/User.php";
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="../../_scripts/utils.js"></script>
<script>
$(function() {
$("#txtText").keydown(function(event) {
var sInput = String.fromCharCode(event.keyCode);
if ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".indexOf(sInput) !== -1) {
console.log(sInput);
} else {
return false;
}
});
});
</script>
<style>
</style>
</head>
<body>
<input id="txtText" />
</body>
</html>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks, Rob!
ASKER
Rob, I thought I'd course this through you since I've pretty much implemented what you told me. I'm having a couple of issues. You can see it here: https://www.experts-exchange.com/questions/28681770/JavaScript-keypress-issues.html.
Thanks.
Thanks.
If you use the keypress event however you'll see that jQuery normalises the "which" property of the event such that it will show the correct character