javascript - กรองตารางด้วย JS และมี "ไม่พบผลลัพธ์"

ฉันได้พยายามหาวิธีรวมคำสั่ง if else เข้ากับโค้ดต่อไปนี้เพื่อส่งคืนแถวเพิ่มในตารางคือผลลัพธ์ = 0 พร้อมข้อความที่ระบุว่า "ไม่พบผลลัพธ์"
โค้ดของฉันคือ:< /p>

//Function for searching products
$(document).ready(function(){
$("#productInput").on("keyup", function() {
let value = $(this).val().toLowerCase();
$("#productTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});

});
});

ไชโย


Answer

วิธีแก้ปัญหา:

หลังจากที่คุณสลับแถวที่ตรงกันทั้งหมดแล้ว ให้นับจำนวนแถวที่มองเห็น หากเป็น 0 ให้เพิ่มแถวที่ระบุว่าไม่พบ


filter() ส่งคืนชุดขององค์ประกอบที่ตรงกับเงื่อนไข คุณไม่ได้ส่งคืนสิ่งใดจากฟังก์ชันการโทรกลับ ดังนั้นคุณควรใช้ .each()


\r
\ r
$(document).ready(function() {
$(\"#productInput\").on(\"keyup\", function() {
let value = $(this).val().toLowerCase();
$(\"#productTable tr.notfound\").remove(); // remove extra row if we added it during previous filter
$(\"#productTable tr\").each(function() {
$(this).toggle($(this).text().toLowerCase().includes(value));
})
if ($(\"#productTable tr:visible\").length == 0) {
$(\"#productTable\").append(\"<tr class=\'notfound\'><td>No results found</td></tr>\");
}
});
});
\r

Source