Search KendoUI Grid dataSource with a textbox

By | June 5, 2014

Here is some code to add a textbox to search a kendo grid, which as a user types filters (client side) the data which the grid is bound to. As you will be using the textbox class to attach the event which will be raised when the user types and setting the id of the grid and the fields which you want to filter as data attributes. You only have to define the javascript once. The html code for the textbox (input element)

<input class="tb-grid-search" data-grid="[The id/name of your grid]" data-field="[The names of the fields to filter, separated by commas]"  />

And the javascript

<script type="text/javascript">
$(".tb-grid-search").on("keyup"function () {
    var $this = $(this);
    var $val = $this.val();
    var operator = "contains";
    switch ($val[0]) {
        case "%":
            $val = $val.replace("%""");
            operator = "startswith";
            break;
        default:
            break;
    }
    var grid = $("#" + $this.data("grid")).data("kendoGrid");
    var filter = { logic: "or", filters: [] };
    $.each($this.data("field").split(','), function(index, field){
        filter.filters.push({field: field, operator: operator, value: $val });
    });
    grid.dataSource.filter(filter);
});
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *