Robert C
Robert C

Reputation: 806

if statement only runs on second key down

Trying to figure out why the if statement here only runs on the second time a user presses a key down. I'm trying to get it to run starting on the first key down.

Function:

const commentFieldHasText = () => {
    const commentInput = document.querySelector('.add-comment')
    console.log('runs first keypress')

    if (commentInput.value) {
      console.log('only runs second keypress')
    }
  }

Input:

 <input 
   className="add-comment"
   placeholder="Add a public comment" 
   onKeyDown={() => commentFieldHasText()}
 />

Additional Info: onKeyPress doesn't give expected functionality either. onKeyUp does though.

Upvotes: 2

Views: 363

Answers (1)

iPhoenix
iPhoenix

Reputation: 737

This happens because the keydown and keypress events occur before the actual key is typed.

To fix this, try using the input or keyup events.

Upvotes: 5

Related Questions