LFReD
LFReD

Reputation: 111

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

When using a fixed header row to implement column-level filters, how can I return cells with a partial match?

ie: search term: "omato"

returns: automator, tomato etc.

Upvotes: 4

Views: 2030

Answers (2)

biofractal
biofractal

Reputation: 19143

Here is the coffeescript code I use to acheive this:

filterGrid = (item) ->
    return true unless hasFilter
    grid.setSelectedRows([])
    columns = grid.getColumns()
    for columnId, filter of columnFilters
        if filter? 
            column = columns[grid.getColumnIndex(columnId)]
            field = item[column.field]
            return false unless (field? && field.toLowerCase().indexOf(filter.toLowerCase()) > -1) 
    return true

The line grid.setSelectedRows([]) just clears any selected rows before applying the filter. If you don't do this then the selected rows you see on-screen do not match the underlying selected rows.

More importantly the return true unless hasFilter line prevents any filtering work whilst the grid is loading, unless the user has actually typed into one of the boxes. I have found that this makes quite a difference to the performance of the grid when loading large datasets in batches of JSON data over http.

Here is the input box handler that sets the hasFilter flag:

$(grid.getHeaderRow()).delegate(':input', 'change keyup', (e) ->
    columnId = $(this).data('columnId')
    if columnId?
        columnFilters[columnId] = $.trim($(this).val())
        hasFilter = true
        dataView.refresh()
)

Upvotes: 0

LFReD
LFReD

Reputation: 111

Under MyFilter in the example replace this loop...

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

with this..

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

Seems so obvious now :)

Upvotes: 6

Related Questions