JQGrid Toolbar Searching: search for multiple words for a column

An interesting question!

I created the demo which demonstrate how to implement multi-word searching:

enter image description here

The corresponding code is:

$grid.jqGrid('filterToolbar', {
    stringResult: true,
    defaultSearch: "cn",
    beforeSearch: function () {
        modifySearchingFilter.call(this, ' ');
    }
});

where modifySearchingFilter I defined in the way:

var modifySearchingFilter = function (separator) {
        var i, l, rules, rule, parts, j, group, str,
            filters = $.parseJSON(this.p.postData.filters);
        if (filters && typeof filters.rules !== 'undefined' && filters.rules.length > 0) {
            rules = filters.rules;
            for (i = 0; i < rules.length; i++) {
                rule = rules[i];
                if (rule.op === 'cn') {
                    // make modifications only for the 'contains' operation
                    parts = rule.data.split(separator);
                    if (parts.length > 1) {
                        if (typeof filters.groups === 'undefined') {
                            filters.groups = [];
                        }
                        group = {
                            groupOp: 'OR',
                            groups: [],
                            rules: []
                        };
                        filters.groups.push(group);
                        for (j = 0, l = parts.length; j < l; j++) {
                            str = parts[j];
                            if (str) {
                                // skip empty '', which exist in case of two separaters of once
                                group.rules.push({
                                    data: parts[j],
                                    op: rule.op,
                                    field: rule.field
                                });
                            }
                        }
                        rules.splice(i, 1);
                        i--; // to skip i++
                    }
                }
            }
            this.p.postData.filters = JSON.stringify(filters);
        }
    };

UPDATE: Free jqGrid supports Custom filtering searching Operation, which makes very easy the implementation of such scenarios like above.

Leave a Comment