How to trigger an event when the user clear a textbox with JavaScript?

Sometimes, we want to trigger an event when the user clear a textbox with JavaScript.

In this article, we’ll look at how to trigger an event when the user clear a textbox with JavaScript.

How to trigger an event when the user clear a textbox with JavaScript?

To trigger an event when the user clear a textbox with JavaScript, we can listen to the input’s keyup event.

For instance, we write:

<input>

to add an input.

Then we write:

const input = document.querySelector('input')
input.onkeyup = () => {
  if (!input.value) {
    console.log('cleared');
  }
}

to select the input with querySelector.

Then we set the input.onkeyup property to a function that check if input.value is an empty string.

If it is, then 'cleared' is logged.

Therefore, when the input is cleared with backspace, we see 'cleared' logged.

Conclusion

To trigger an event when the user clear a textbox with JavaScript, we can listen to the input’s keyup event.