input changes getting previous value

Viewed 39

I'm getting the previous value in console when i write in the input, how can i get the actual value?

const input1 = document.querySelector('#a')

input1.addEventListener('keypress', (e) => {
    console.log(e.target.value)
})
<input type="text" id="a" />

enter image description here

3 Answers

Try eventListener input. Keydown is fired before the character is added to the field, which is why you don't see the 4 after typing 1234. (An if you prevent the default action of keydown, the character is never added.) keyup is also fired after the character is added.

const input1 = document.querySelector('#a')

input1.addEventListener('input', (e) => {
    console.log(e.target.value)
})
<input type="text" id="a" />

The easiest way is just to change keydown to keyup event listener. It will work for your case.

input1.addEventListener('keyup', (e) => {
   console.log(e.target.value)
})

A better way will be if you use event listener "input".

input1.addEventListener('input', (e) => {
   console.log(e.target.value)
})

hello freind i want provide you how to listen input event

if this case have many method:

1)

<input name="name" id="a"/>
document.querySelector("input#a").addEventListener("input",function(event){
console.log(event.target.value);})
Related