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
.... 
...... 
nosdalg
  • 571
  • 1
  • 5
  • 23

1 Answers1

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

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 1
    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. – Sunil Kumar May 08 '15 at 06:00