Customizing Search in Kendo UI Grid Toolbar to Trigger on Enter Key Press
Environment
Product | Grid for Progress® Kendo UI® |
Version | 2024.3.1015 |
Description
I want to customize the search option in the grid toolbar so that the search is triggered not by the change event but by pressing the Enter key. In my Grid, serverFiltering
is enabled. This KB article also answers the following questions:
- How to prevent the Kendo UI Grid from searching on every keypress?
- How to make the Kendo UI Grid search work with the Enter key press?
- How to customize the Kendo UI Grid search functionality with serverFiltering enabled?
Solution
To customize the search functionality in the Kendo UI Grid so that it triggers only on an Enter key press, especially when serverFiltering
is enabled, follow these steps:
- Attach a handler to the
keydown
event of the search box. - Check the pressed key. If it is not 'Enter', prevent the
dataSource request
from firing. - If the user presses 'Enter', manually apply the filter.
Here is the JavaScript code demonstrating the solution:
$(".k-grid-search input").on("keydown", function(e) {
let grid = $("#grid").data("kendoGrid");
let filters = grid.dataSource.filter();
if(e.keyCode != 13){
grid.dataSource.one("requestStart", function(e) {
e.preventDefault();
});
}else{
if(filters) {
grid.dataSource.filter(filters);
} else {
grid.dataSource.filter([]);
}
}
});
Below is a runnable example:
<div id="grid"></div>
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
height: 550,
toolbar: ["search"],
messages: {
commands: {
search: "rechercher"
}
},
search: {
fields: [
{ name: "OrderID", operator: "eq" },
{ name: "Freight", operator: "gte" },
{ name: "ShipName", operator: "contains" },
{ name: "ShipCity", operator: "contains" }
]
},
columns: [
{
field: "OrderID",
title: "Order ID",
},
"Freight",
{
field: "ShipName",
title: "Ship Name"
}, {
field: "ShipCity",
title: "Ship City"
}
]
});
$(".k-grid-search input").on("keydown", function(e) {
let grid = $("#grid").data("kendoGrid");
let filters = grid.dataSource.filter();
if(e.keyCode != 13){
grid.dataSource.one("requestStart", function(e) {
e.preventDefault();
});
}else{
if(filters) {
grid.dataSource.filter(filters);
} else {
grid.dataSource.filter([]);
}
}
});
});
</script>