1

My requirement is on a keypress I need to get the value of the particular textbox. But the problem is when I press the first letter am getting a blank output. on second keypress am getting the first letter which I have entered in the textbox. Form here on Its getting a one step delay. Is am missing anything.

 <script>
     document.addEventListener('keypress',function(e){
           var keycode = e.keyCode || e.which;
           if(document.activeElement.id == 'k_id_234'){
                console.log(document.getElementById('k_id_234').value);

           }
     });
   </script>
<input type="text" id="k_id_234">

Text Box : h    console :     // empty
Text Box : he   console : h   //only first letter
.... 
...... 

1 Answer 1

5

Use keyup event instead

document.addEventListener('keyup', function (e) {
    var keycode = e.keyCode || e.which;
    if (document.activeElement.id == 'k_id_234') {
        console.log(document.getElementById('k_id_234').value);

    }
});

Demo: Fiddle


Another option is the input event

Sign up to request clarification or add additional context in comments.

1 Comment

Supporting the answer by @Arun - # keyup(): Event fired when a key is released on the keyboard. # keydown(): Event fired when a key is pressed on the keyboard. # keypress:() Event fired when a key is pressed on the keyboard. In case if you press any special key, browser will fire only keydown() event but not keypress() event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.