TabulatorPlus: Global Search

การเพิ่ม Global Search เข้าไปใน TabulatorPlus เป็นฟีเจอร์ที่ยอดเยี่ยมมากครับ เพราะโดยปกติ Tabulator จะกรองข้อมูลแยกตามคอลัมน์ แต่การมี “ช่องค้นหาเดียวที่ค้นทุกอย่าง” จะช่วยให้ User Experience (UX) ดีขึ้นมาก


🛠 เพิ่ม Method ใน TabulatorPlus.js

/** * 4. Global Search Method * Filters the table across multiple columns based on a single search string. * @param {string} searchTerm - The string to search for. * @param {Array} columnsToSearch - Optional array of field names to search in. * If empty, it will search all visible columns. */ globalSearch (searchTerm, columnsToSearch = []) { // If search term is empty, clear all filters if (!searchTerm || searchTerm.trim () === "") { this.clearFilter () ; return; } // Get all column definitions if no specific columns provided const cols = columnsToSearch.length > 0 ? columnsToSearch : this.getColumnDefinitions () .filter (col => col.field) // Only columns with data fields .map (col => col.field) ; // Build a filter array for Tabulator (using OR logic) const filterArray = cols.map (field => { return { field: field, type: "like", value: searchTerm }; }) ; // Apply the filter using Tabulator's setFilter with 'OR' logic // We pass the array of filters as the first argument to treat it as an 'OR' group this.setFilter ([filterArray]) ; }

💡 วิธีการใช้งานในหน้าเว็บ

เมื่อคุณมี Method นี้แล้ว การเชื่อมต่อกับ Input กรองข้อมูลจะง่ายมากครับ


ตัวอย่างการใช้กับ HTML / JavaScript ทั่วไป

const myTable = new TabulatorPlus ("#table", { /* config */ }) ; // เมื่อพิมพ์ในช่องค้นหา
$ ("#global-search-input") .on ("keyup", function () { const value = $ (this) .val () ; myTable.globalSearch (value) ;
}) ;

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

function MyTableComponent () { const tableRef = useRef (null) ; const instance = useRef (null) ; const handleSearch = (e) => { if (instance.current) { instance.current.globalSearch (e.target.value) ; } }; return ;
}

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

let searchTimer;
const onSearchInput = (e) => { clearTimeout (searchTimer) ; searchTimer = setTimeout ( () => { myTable.globalSearch (e.target.value) ; }, 300) ; // รอให้หยุดพิมพ์ 300ms ค่อยเริ่มค้นหา
};

✨ ทำไมฟังก์ชันนี้ถึงเจ๋ง ?

  • OR Logic: ตามปกติถ้าคุณใช้ setFilter หลายครั้ง Tabulator จะใช้ AND แต่โค้ดนี้ใช้ [ [filter1, filter2] ] ซึ่งบอก Tabulator ให้ใช้ OR
  • Flexible Columns: คุณสามารถระบุได้ว่าจะให้ค้นหาแค่บางคอลัมน์เพื่อความเร็ว เช่น globalSearch ("john", ["fname", "lname"]) หรือปล่อยว่างไว้เพื่อให้ค้นหาทุกคอลัมน์ที่มี field
  • Automatic Cleanup: ถ้าส่งค่าว่างมา ระบบจะเรียก clearFilter () ให้โดยอัตโนมัติ เพื่อดึงข้อมูลทั้งหมดกลับมาโชว์

⚠️ ข้อควรระวัง

การใช้ like ใน globalSearch กับข้อมูลจำนวนมหาศาล บน Client-side อาจทำให้หน่วงเล็กน้อย หากข้อมูลเยอะมาก แนะนำให้ทำ Debounce ครับ


อ่านเพิ่มเติม

Exit mobile version