Add oninput attribute to HTML element with JavaScript?

You can add the oninput attribute to HTML elements using JavaScript in two ways: using addEventListener() or directly setting the oninput property. Both methods allow you to dynamically attach input event handlers to elements.

Using addEventListener() (Recommended)

The addEventListener() method is the modern approach for attaching event listeners:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add oninput with addEventListener</title>
</head>
<body>
    <label>Enter the value:</label>
    <input id="enterValue" type="text">
    <p id="output"></p>

    <script>
        document.getElementById('enterValue').addEventListener("input", function () {
            document.getElementById('output').textContent = 'You entered: ' + this.value;
        });
    </script>
</body>
</html>

Using oninput Property

You can also directly assign a function to the oninput property:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add oninput with Property</title>
</head>
<body>
    <label>Enter text:</label>
    <input id="textInput" type="text">
    <p id="display"></p>

    <script>
        document.getElementById('textInput').oninput = function() {
            document.getElementById('display').textContent = 'Current input: ' + this.value;
        };
    </script>
</body>
</html>

Adding oninput to Multiple Elements

You can apply input handlers to multiple elements using a loop:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiple Input Handlers</title>
</head>
<body>
    <input class="textInput" type="text" placeholder="Input 1">
    <input class="textInput" type="text" placeholder="Input 2">
    <input class="textInput" type="text" placeholder="Input 3">
    <div id="result"></div>

    <script>
        const inputs = document.querySelectorAll('.textInput');
        
        inputs.forEach(function(input, index) {
            input.addEventListener('input', function() {
                document.getElementById('result').innerHTML = 
                    `Input ${index + 1} changed: ${this.value}`;
            });
        });
    </script>
</body>
</html>

Comparison

Method Multiple Handlers Recommended
addEventListener() Yes Yes
oninput property No No

Conclusion

Use addEventListener('input', function) to dynamically add input handlers to HTML elements. This approach is more flexible and allows multiple event handlers on the same element.

Updated on: 2026-03-15T23:18:59+05:30

659 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements