ConorReidd
ConorReidd

Reputation: 276

Keyup input not getting value

I'm trying to write a small script so whenever the user inputs some text on the webpage it will get me the value instantly. Unfortunately the Keyup() JQUERY function is returning no value when I try to test it.

$(document).ready(function() {
    $(document).keyup(function() {
        var command = $(this).val();
        alert(command);
    });
});

The alert shows no text what-so-ever and i'm unsure why?

Upvotes: 0

Views: 3480

Answers (4)

Vikas
Vikas

Reputation: 39

  1. There are various ways to fix it. It is like two way binding.

  2. You can play with keyup/keydown events of jquery

  3. Other wise you can prefer AngularJS which has built in functionality of two way binding.

Upvotes: -1

Divyesh Savaliya
Divyesh Savaliya

Reputation: 2740

Your selector is $(document) which has no value.
You can get value only if your selector is any input.
If you want to get character type by user then try it as follow

$(document).keyup(function(e) {
    var command = String.fromCharCode(e.which);
    alert(command);
});

Upvotes: 4

Max
Max

Reputation: 95

Try this code.

<!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>   
    </head>
    <body>
    <script type="text/javascript">
    $(document).ready(function() {
        $("input").keyup(function() {
            var command = $(this).val();
            alert(command);
        });
    });
    </script>
    <input type="text">
    </body>
    </html>

Upvotes: 2

Diljohn5741
Diljohn5741

Reputation: 434

I have modified the snippet

$(document).ready(function() {
$(document).keyup(function(e) {
    var command = $(e.target).val()
    alert(command);
});
});

$(this) always remain where you are binding the event which is document in your case but e.target provides current element where you are using your event.

Upvotes: 0

Related Questions