Rumah  >  Artikel  >  hujung hadapan web  >  Bagaimana untuk Menjejaki Perubahan Masa Nyata dalam Medan Input Teks?

Bagaimana untuk Menjejaki Perubahan Masa Nyata dalam Medan Input Teks?

Susan Sarandon
Susan Sarandonasal
2024-11-14 21:24:02265semak imbas

How to Track Real-Time Changes in Text Input Fields?

Best Way to Track Real-Time Changes in Input Text 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.

Browser Support for On-the-Fly Tracking

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.

Cross-Browser Compatibility

For older browsers, including IE8 and below, a combination of the onpropertychange event and the oninput event can ensure cross-browser compatibility.

A Code Example

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.

Atas ialah kandungan terperinci Bagaimana untuk Menjejaki Perubahan Masa Nyata dalam Medan Input Teks?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn