Helpful JavaScript Methods for the Telerik Grid for ASP.NET MVC
The Telerik MVC Grid is quite a cool component. Nevertheless, some client-side API functions are desperately missing. For example, you cannot select or deselect rows by code. Also, there’s no way to do client-side-filtering (i.e. hide rows based on values withoud re-populating the whole grid). So here is a set of some functions that were helpful to me – suite yourselves…
01.``//
02.``// In a hierarchical grid, the function returns the parent row of the specified child row.
03.``//
04.``function getParentRow(row) {
05.`` ``var l = $(row).parents(``'.t-detail-row'``).prev();
06.`` ``return l.length == 0 ? ``null : l[0];
07.``}
08.
09.``//
10.``// In a hierarchical grid, the function returns the child grid of the specified parent row.
11.``//
12.``function getChildGrid(row) {
13.`` ``var nextRow = $(row).next();
14.`` ``return nextRow.hasClass(``'t-detail-row'``) ? $(``'.t-grid'``, nextRow).data(``'tGrid'``) : ``null``;
15.``}
16.
17.``//
18.``// Selects the specified row. The row will be highlighted and the onRowSelect event handler will be called.
19.``//
20.``function selectRow(row) {
21.`` ``var $row = $(row);
22.`` ``$row.addClass(``'t-state-selected'``);
23.`` ``var grid = $row.parents(``'.t-grid'``).data(``'tGrid'``);
24.`` ``if``(grid.onRowSelect) grid.onRowSelect({ row: row });
25.``}
26.
27.``//
28.``// Unselects all rows in the specified grid.
29.``//
30.``function unselectRows(grid) {
31.`` ``$(grid.$rows()).removeClass(``'t-state-selected'``);
32.``}
33.
34.``//
35.``// Unselects the specified row.
36.``//
37.``function unselectRow(row) {
38.`` ``$(row).removeClass(``'t-state-selected'``);
39.``}
40.
41.``//
42.``// Hides all rows in the specified grid that have a data member that equals teh specified value.
43.``// If the data member is omitted, all rows get shown again.
44.``//
45.``function filterWhenEquals(grid, dataMember, value) {
46.`` ``var columnIndex = -1;
47.
48.`` ``if (dataMember) {
49.`` ``$.each(grid.columns, ``function (i, c) {
50.`` ``if (c.member == dataMember) {
51.`` ``columnIndex = i;
52.`` ``}
53.`` ``});
54.`` ``}
55.
56.`` ``if (columnIndex >= 0) {
57.`` ``grid.$rows().each(``function (i, r) {
58.`` ``if ($($(``'td'``, r)[columnIndex]).html() != value) {
59.`` ``$(r).hide();
60.`` ``}
61.`` ``else {
62.`` ``$(r).show();
63.`` ``}
64.`` ``});
65.`` ``}
66.`` ``else { $(grid.$rows()).show(); }
67.``}
Category: JavaScript