jQuery - ตัวกรอง
ตัวกรอง jQuery
ใช้ jQuery เพื่อกรอง/ค้นหาองค์ประกอบเฉพาะ
ตารางกรอง
ทำการค้นหาโดยคำนึงถึงขนาดตัวพิมพ์สำหรับรายการในตาราง:
ตัวอย่าง
Type something in the input field to search the table for first names, last names or emails:
Firstname | Lastname | |
---|---|---|
John | Doe | [email protected] |
Mary | Moe | [email protected] |
July | Dooley | [email protected] |
Anja | Ravendale | [email protected] |
jQuery
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var
value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
ตัวอย่างที่อธิบาย:เราใช้ jQuery เพื่อวนซ้ำในแต่ละแถวของตารางเพื่อตรวจสอบว่ามีค่าข้อความที่ตรงกับค่าของฟิลด์อินพุตหรือไม่ วิธี การtoggle()
ซ่อนแถว ( display:none
) ที่ไม่ตรงกับการค้นหา เราใช้toLowerCase()
เมธอด DOM เพื่อแปลงข้อความเป็นตัวพิมพ์เล็ก ซึ่งทำให้ตัวพิมพ์เล็กและตัวพิมพ์ใหญ่ในการค้นหาไม่มีความสำคัญ (อนุญาตให้ใช้ "john", "John" และแม้แต่ "JOHN" ในการค้นหา)
กรองรายการ
ทำการค้นหาโดยคำนึงถึงขนาดตัวพิมพ์สำหรับรายการในรายการ:
ตัวอย่าง
Type something in the input field to search the list for items:
- First item
- Second item
- Third item
- Fourth
กรองอะไรก็ได้
ทำการค้นหาข้อความภายในองค์ประกอบ div โดยคำนึงถึงขนาดตัวพิมพ์:
ตัวอย่าง
I am a paragraph.
Another paragraph.