Event onsearch ทริกเกอร์เมื่อ User กด Enter หรือกดปุ่ม Clear (✕) ใน <input type="search">
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body>
<p>Write what you want to search below and press "ENTER".</p>
<input type="search" id="newInput" onsearch="searchFunc()">
<script>
function searchFunc() {
var a = document.getElementById("newInput");
document.write("Searched = " + a.value);
}
</script>
</body>
</html>
คำอธิบาย
- ทำงานเฉพาะ
<input type="search">(ไม่ใช่ type="text") - ทริกเกอร์: กด Enter, กดปุ่ม Clear (✕), หรือ Voice Search Submit
- ไม่ทริกเกอร์ เมื่อพิมพ์ปกติ (ใช้
oninputแทน)
⚠️ Browser Support
| Browser | Support |
|---|---|
| Chrome/Edge/Safari | ✅ รองรับ |
| Firefox | ❌ ไม่รองรับ (ใช้ input + Enter Check) |
| IE | ❌ ไม่รองรับ |
Cross-browser Alternative (แนะนำ)
const searchInput = document.querySelector('input[type="search"]');
// Method 1: input + Enter Key (รองรับทุก Browser)
searchInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
doSearch(searchInput.value);
}
});
// Method 2: form submit (Semantic)
/*
*/
Search Input Features
- แสดงปุ่ม Clear (✕) อัตโนมัติเมื่อมีค่า
- รองรับ Voice Input (Mobile)
- Browser อาจเพิ่ม Search History/Recent Dropdown
- CSS:
::-webkit-search-cancel-buttonสไตล์ปุ่ม Clear