Home > OS >  input changes getting previous value
input changes getting previous value

Time:09-18

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

CodePudding user response:

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" />

CodePudding user response:

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)
})
  • Related