Search code examples
javascriptjqueryhtmlkeyup

keyevent in jQuery not working


I've got an HTML element that I want to fill with specific content after someone presses "1" on the keyboard. I use an external .js file which contains the following code:

$(document).ready(function() {
    $("#myid").html("Hello, 0111");
    $("#myid2").html("Lorem Ipsum");


    $(document).keyup(function (pressed_key) {
        if (pressed_key.key === "1") { 
            $("#myid").html("Button pressed");

            setTimeout(function () {
                $("#myid").html("Button not pressed");
            }, 1000);
        } 
    }

});

My HTML body looks like this:

<body>
    <div id="myid">0129</div>
    <div id="myid2"></div>
    <script src="js/libs/jquery/jquery.min.js"></script>
    <script src="js/script.js"></script>
</body>

The code is not working, it outputs the content of the HTML document.

However, if I comment out the .keyup function, the rest of the JavaScript code works and changes the HTML content accordingly.

Any ideas?


Solution

  • The issue is because the argument passed to the keyup handler is the event, not the value of the character which was typed.

    To fix this you can use String.fromCharCode(), along with the which property of the event, to get the character, like this:

    $(document).ready(function() {
      $("#myid").html("Hello, 0111");
      $("#myid2").html("Lorem Ipsum");
    
      $(document).keyup(function(e) {
        if (String.fromCharCode(e.which) === "1") {
          $("#myid").html("Button pressed");
    
          setTimeout(function() {
            $("#myid").html("Button not pressed");
          }, 1000);
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="myid">0129</div>
    <div id="myid2"></div>