2

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.

Mamun
  • 66,969
  • 9
  • 47
  • 59
jsdev17
  • 1,050
  • 2
  • 15
  • 25

2 Answers2

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.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input: <input type='text' id="txtInput"/>
Mamun
  • 66,969
  • 9
  • 47
  • 59
4

$( "#whichkey" ).on( "keydown", function( event ) {
  $( "#log" ).html( event.type + ": " +  event.which );
});
<script src="https://ajax.googleapis.com/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.

guradio
  • 15,524
  • 4
  • 36
  • 57