简体   繁体   中英

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');
            });
        });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM