Home >Web Front-end >JS Tutorial >How to Track Real-Time Changes in Text Input Fields?
When utilizing input type="text," the onchange event often happens only after the user leaves focus from the field. This can be problematic if the need is to track changes as they're made.
Modern browsers offer a solution through the oninput event. This event is triggered every time the content of the text field changes. It's a near-perfect replacement for onchange, providing real-time monitoring without the need to lose focus from the element. It's supported by all major browsers, including mobile browsers.
For older browsers, including IE8 and below, a combination of the onpropertychange event and the oninput event can ensure cross-browser compatibility.
Here's an example code to showcase how to use oninput and onpropertychange for cross-browser tracking:
const source = document.getElementById('source'); const result = document.getElementById('result'); const inputHandler = function(e) { result.innerText = e.target.value; } source.addEventListener('input', inputHandler); source.addEventListener('propertychange', inputHandler); // For completeness, include listen for option changes which won't trigger either input or change source.addEventListener('change', inputHandler);
For browsers that don't support oninput or onchange, the setTimeout function can be used as an alternative, but it's not as elegant or efficient as the aforementioned solutions.
The above is the detailed content of How to Track Real-Time Changes in Text Input Fields?. For more information, please follow other related articles on the PHP Chinese website!