Kenneth
Kenneth

Reputation: 43

How do I detect when input value changes real-time in JavaScript?

I'm trying to get my input field element to remove a class immediately after the input value changes. Currently, I'm able to detect the changes and remove the class 'invalid', but only after the input field is inactive. Here's my code;

fieldsArr.forEach(el => {
            el.addEventListener('change', function() {
                this.classList.remove('invalid');
            });
        });

Upvotes: 4

Views: 10990

Answers (2)

Arturas Lapinskas
Arturas Lapinskas

Reputation: 336

If you want to listen for events, your elemet should be extended from EventEmitter.

Upvotes: -2

DaCurse
DaCurse

Reputation: 825

Use the input event instead, as the name suggests it would fire each time an input is made, see this example on how to use the event:

let inputElem = document.querySelector('input');

inputElem.addEventListener('input', () => {
  console.log(inputElem.value); // Log the new value after an input is made
});
<input />

Upvotes: 13

Related Questions