Can I prevent enter key press from calling change event of Input tag?

24 views Asked by At

change event is required for other scenario but that shouldnt get triggered on enter key press.

JSFiddle : https://jsfiddle.net/Ljwa10es/1/

Sample Input

const inp = document.querySelector("#inp");
inp.addEventListener("change", changeHandler);
inp.addEventListener("keyup", keyupHandler);

function changeHandler(e) {
      console.log(e.target.value)
}

function keyupHandler(e) {
    if (e.keyCode === 13) {
        console.log("Enter key pressed")
    }
}

change event is required for other scenario but that shouldnt get triggered on enter key press.

1

There are 1 answers

2
Santhosh Gurunathan On
  const inp = document.querySelector("#inp");
  inp.addEventListener("change", changeHandler);
  inp.addEventListener("keyup", keyupHandler);

  function changeHandler(e) {
        console.log(e.target.value)
  }

  function keyupHandler(e) {
        if (e.keyCode === 13) {
              e.preventDefault();
        }else{
              console.log("Enter key was not pressed")
        }
  }

You would have to stop the keyup function from triggering the change function by using the preventDefault method.