admin管理员组

文章数量:1279182

Working on a simple hangman game, and I'm trying to catch the user input with the keyup(), but when I log it to the console I'm realizing something isn't working right... this is my code:

$(document).keyup(function(e) {

    userInput = e.value;
    console.log(userInput);

});

I also tried doing this, but it isn't working either.

$(document).keyup(function(e) {

    userInput = $(this).val();
    console.log(userInput);

});

oh, by the way, userInput is a global variable.

Working on a simple hangman game, and I'm trying to catch the user input with the keyup(), but when I log it to the console I'm realizing something isn't working right... this is my code:

$(document).keyup(function(e) {

    userInput = e.value;
    console.log(userInput);

});

I also tried doing this, but it isn't working either.

$(document).keyup(function(e) {

    userInput = $(this).val();
    console.log(userInput);

});

oh, by the way, userInput is a global variable.

Share Improve this question edited Mar 25, 2018 at 11:45 Mamun 68.9k9 gold badges51 silver badges62 bronze badges asked Mar 15, 2017 at 4:58 jsdev17jsdev17 1,1103 gold badges16 silver badges25 bronze badges 5
  • you tried to debug it ???. what you get in e ? – Brave Soul Commented Mar 15, 2017 at 5:00
  • 2 e.which? try it – guradio Commented Mar 15, 2017 at 5:00
  • 2 Possible duplicate of jQuery Event Keypress: Which key was pressed? – Alexander Nied Commented Mar 15, 2017 at 5:02
  • Possible duplicate: stackoverflow./questions/302122/… – Alexander Nied Commented Mar 15, 2017 at 5:02
  • when I use e.value I get undefined back. when I do $(this).val(), I get a blank space back. e.which gives me the ASCII code, but not the actual letter... – jsdev17 Commented Mar 15, 2017 at 5:19
Add a ment  | 

2 Answers 2

Reset to default 8

You have to get the value from target property of the event. Try the following way:

$('#txtInput').on('keyup', function(e) {

    var userInput = e.target.value;
    console.log(userInput);

});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input: <input type='text' id="txtInput"/>

$( "#whichkey" ).on( "keydown", function( event ) {
  $( "#log" ).html( event.type + ": " +  event.which );
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="whichkey" placeholder="type something">
<div id="log"></div>

Use event.which

Description: For key or mouse events, this property indicates the specific key or button that was pressed.

本文标签: javascriptHow to catch keyboard input with jQuery keyup() functionStack Overflow