Ajay K
Ajay K

Reputation: 446

OnKeydown first character is not captured

I want to capture an event data from the textbox but it returns empty for the text entered. Can you tell me what am I doing wrong here? The name is not alerted for the first character entered. Please help.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script>
        $(function() {
            $("#name").keydown(function(event){
                var name = $("#name").val();
                alert("name" + name);
            });
        });
    </script>
</head>
<body>
    <input id="name">
</body>
</html>

Upvotes: 0

Views: 250

Answers (2)

Haseeb Asif
Haseeb Asif

Reputation: 1786

You're getting value of textbox even before it has been set. You should try to get the value from event arguments. You can get the press key with event.keycode as follows

$(function() {
      $("#name").keydown(function(event){
            // Just to make sure it works in all browsers
            var keycode = (event.keyCode ? event.keyCode : event.which);
            var userInput = String.fromCharCode(keycode);
             alert("name"+userInput );
      });
  });

Upvotes: 0

Anand Dwivedi
Anand Dwivedi

Reputation: 1500

$(document).ready(function() {
$("#name").keyup(function() {
var dInput = $(this).val();
alert(dInput);
     });});

Try the above Code . or see Demo :Demo

Upvotes: 1

Related Questions