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

Exception or error:

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');
            });
        });
How to solve:

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 />

###

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

Leave a Reply

Your email address will not be published. Required fields are marked *