javascriptfilterslickgridheader-row

Partial Matches When Filtering SlickGrid


Since I don't have enough reputation to comment, I am posting this as a separate question. I am trying to implement the solution given by the user LFReD as an answer to this question:

How to perform partial matches when filtering Slickgrid using column-level headers?

When I use this from original SlickGrid example:

function filter(item) {
for (var columnId in columnFilters) {
  if (columnId !== undefined && columnFilters[columnId] !== "") {
    var c = mygrid.getColumns()[mygrid.getColumnIndex(columnId)];
    if (item[c.field] != columnFilters[columnId]) {
      return false;
    }
  }
}
return true;
}

it works when I type complete word. Partial matches are not performed.

But, to perform partial matching, when I replace the code with

function filter(item) {
for (var columnId in columnFilters) {
    if (columnId !== undefined && columnFilters[columnId] !== "") {
        var c = mygrid.getColumns()[mygrid.getColumnIndex(columnId)];
        if (item[c.field].indexOf(columnFilters[columnId]) == -1) {
            return false;
        }
    }
}
    return true;
}

I get the error javascript error in console which reads "Uncaught TypeError: Object 1 has no method 'indexOf' "

I am not able to figure out what is missing in my code. Since previous code is working fine, it implies that I have already included necessary scripts in my HTML code. Still something seems to be missing. Where am I going wrong?


Solution

  • Change the following line:

    if (item[c.field].indexOf(columnFilters[columnId]) == -1) {
    

    to:

    if (!(item[c.field] && (""+item[c.field]).indexOf(columnFilters[columnId]) !== -1)) {
    

    Final product:

    function filter(item) {
      for (var columnId in columnFilters) {
        if (columnId !== undefined && columnFilters[columnId] !== "") {
          var c = mygrid.getColumns()[mygrid.getColumnIndex(columnId)];
          if (!(item[c.field] && (""+item[c.field]).indexOf(columnFilters[columnId]) !== -1)) {
            return false;
          }
        }
      }
      return true;
    }