Darlyn
Darlyn

Reputation: 4938

Detecting the value on input

Having an input element

<input type="text">

if i add keydown event on it , it will work with state x - 1 value of input e.g

var x = document.getElementsByTagName("input")[0];
x.addEventListener("keydown",function(){
    alert(x.value);
},false);

if i input "a" , it will print empty string , when i add "b" it wont print "ab" but "a" ( state - 1 )

Is there any simple way how to retrieve current value not previous?

Upvotes: 0

Views: 24

Answers (3)

Alex Kudryashev
Alex Kudryashev

Reputation: 9460

As pointed in other answers, you can use keyup or keypress or input if you don't need to cancel event.
If you do need to cancel event (conditionally) then keydown is the must.

var x = document.getElementsByTagName("input")[0];
x.addEventListener("keydown",function(e){
    //alert(x.value);
    console.log(x.value + String.fromCharCode(e.which || e.keyCode);
},false);

The event doesn't support character value but you can receive it from keyCode.

Upvotes: 1

Teja
Teja

Reputation: 1254

Use keyup event or keypress event.

Reason is simple, when you are typing, there are three states.

  1. When the key is pressed and held(even for a very short time). Here, the input field is not yet updated. This is keydown

  2. keyup is when the key is released. That is when the input field is updated.

  3. keypress is keydown and keyup both combined. (For alphanumeric keys)

Upvotes: 2

700 Software
700 Software

Reputation: 87763

Use input instead of keydown event.

If you require older browser support then you should also listen for keyup and mouseup (drag/drop) events.

Upvotes: 2

Related Questions