JavaScript input Event

Summary: in this tutorial, you’ll learn about the JavaScript input event that fires whenever the value of the <input>, <select>And <textarea> changes.

Introduction to the JavaScript input event

The input event fires every time whenever the value of the <input>, <select>, or <textarea> element changes.

Unlike the change event that only fires when the value is committed, the input event fires whenever the value changes.

For example, if you’re typing on the <input> element, the element fire the input event continuously. However, the change event only fires when the <input> element loses focus.

The following example illustrates the input event of the <input> element:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript input Event Demo</title>
</head>
<body>
    <label for="message">Message</label>
    <input placeholder="Enter some text" id="message" name="message">
    <p id="result"></p>
    <script>
        const message = document.querySelector('#message');
        const result = document.querySelector('#result');
        message.addEventListener('input', function () {
            result.textContent = this.value;
        });
    </script>
</body>
</html>Code language: HTML, XML (xml)

How it works:

  • First, select the <input> element with the id message and the <p> element with the id result.
  • Then, attach an event handler to the input event of the <input> element. Inside the input event handler, update the textContent property of the <p> element.
Was this tutorial helpful ?