javascriptgridjsjs-search

How to customize searchable fields with selector in gridjs


In gridjs there is an the example of using selector in search field.

const grid = new Grid({
  columns: [
   {
     name: 'Name',
     formatter: (cell) => cell.firstName
   }, 
   'Email',
   'Phone Number'
  ],
  search: {
    selector: (cell, rowIndex, cellIndex) => cellIndex === 0 ? cell.firstName : cell
  },
  data: [
    [{ firstName: 'John', lastName: 'MP' }, 'john@example.com', '(353) 01 222 3333'],
    [{ firstName: 'Mark', lastName: 'Blue' }, 'mark@gmail.com',   '(01) 22 888 4444'],
  ]
});

But from the example it's not quite clear how to reduce search to only 'Email' and 'Phone Number' fields?


Solution

  • You have to specify a selector to which the search is going to run against. In the example, it's specified as the firstName as long as the search is running against the first cell, i.e., the line cellIndex === 0. Thus, if you want to have the search run against a specific cell/column, you'd have to write a conditional for its specific cell location/index.

    Here is an example that filters based on Email & Phone Number:

    const grid = new Grid({
      columns: [
       {
         name: 'Name',
         formatter: (cell) => cell.firstName
       }, 
       'Email',
       'Phone Number'
      ],
      search: {
        selector: (cell, rowIndex, cellIndex) => {
          if (cellIndex === 1) return cell;
          
          if (cellIndex === 2) return cell;
        }
      },
      data: [
        [{ firstName: 'John', lastName: 'MP' }, 'john@example.com', '(353) 01 222 3333'],
        [{ firstName: 'Mark', lastName: 'Blue' }, 'mark@gmail.com',   '(01) 22 888 4444'],
      ]
    });
    
    

    Or for conciseness:

    const grid = new Grid({
      columns: [
       {
         name: 'Name',
         formatter: (cell) => cell.firstName
       }, 
       'Email',
       'Phone Number'
      ],
      search: {
        selector: (cell, rowIndex, cellIndex) => {
            if (cellIndex !== 0) return cell;
        }
      },
      data: [
        [{ firstName: 'John', lastName: 'MP' }, 'john@example.com', '(353) 01 222 3333'],
        [{ firstName: 'Mark', lastName: 'Blue' }, 'mark@gmail.com',   '(01) 22 888 4444'],
      ]
    });
    

    In the latter example, I match the search selector against all the cell indices/fields except for the first cell(Name field). Hope this helps! :)