Link to home
Start Free TrialLog in
Avatar of elepil
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:

<?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>

Open in new window

Avatar of Rob
Rob
Flag of Australia image

You would have to do this mapping yourself but event.shiftKey you'll notice is true so it detects that you've pressed the "3" key with the "shift" key held down.

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
ASKER CERTIFIED SOLUTION
Avatar of Rob
Rob
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of elepil
elepil

ASKER

Thanks, Rob!
Avatar of elepil

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.