Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

เหตุการณ์ onsearch: รันสคริปตเมื่อผู้ใช้ค้นหาในช่องค้นหา

เหตุการณ์ onsearch จะถูกกระตุ้นเมื่อผู้ใช้พิมพ์ในช่องค้นหา (<input type="search">) และกด Enter หรือกดปุ่ม Clear (เครื่องหมาย X) หมายเหตุ: ไม่รองรับใน Internet Explorer และ Firefox

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<body>
    <p>ค้นหาบางอย่างและกด Enter</p>
    <input type="search" id="inputID" onsearch="display()" placeholder="พิมพ์คำค้นหา...">
    <p><strong>หมายเหตุ:</strong> ไม่ทำงานใน Internet Explorer และ Firefox</p>
    <p id="test"></p>
    <script>
        function display() {
            const input = document.getElementById("inputID");
            document.getElementById("test").innerHTML = "ค้นหา: " + input.value;
        }
    </script>
</body>
</html>

วิธีที่รองรับทุกเบราว์เซอร์ (Cross-browser)

<input type="search" id="searchInput" placeholder="ค้นหา...">

<script>
    const input = document.getElementById('searchInput');
    
    // วิธี 1: ใช้ event 'search' (Chrome, Safari, Edge)
    input.addEventListener('search', (e) => {
        console.log('Search event:', e.target.value);
    });
    
    // วิธี 2: จับ Enter key (ทุกเบราว์เซอร์)
    input.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            console.log('Enter pressed:', e.target.value);
            performSearch(e.target.value);
        }
    });
    
    // วิธี 3: จับการเปลี่ยนแปลง (Live search)
    let debounceTimer;
    input.addEventListener('input', (e) => {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => {
            console.log('Live search:', e.target.value);
            // liveSearch(e.target.value);
        }, 300);
    });
</script>

แอตทริบิวต์เพิ่มเติมของ type="search"

  • incremental - ส่ง event 'search' ทุกครั้งที่พิมพ์ (Safari)
  • results - จำนวนรายการแสดงใน dropdown ประวัติ (Safari)
  • autosave - ชื่อสำหรับเก็บประวัติการค้นหา (Safari)