Mastering jqGrid: Tips and Tricks
jqGrid is a powerful JavaScript grid library for creating interactive and feature-rich tables in web applications. In this article, we’ll explore some useful jqGrid tips and tricks to enhance your grid-building skills.
Changing Column Heading Alignment
One common requirement in jqGrid is to customize the alignment of column headings. This JavaScript function allows you to change the alignment of a specific column heading within a jqGrid table.
function jQGridAlignHeading(tableName, headingName, alignmentType) {
$('#jqgh_' + tableName + '_' + headingName).css({
'text-align': alignmentType,
'padding-right': '12px'
});
}
Usage example:
loadComplete: function (data) {
jQGridAlignHeading('yourGridId', 'ColumnName', 'center');
}
Adding Custom Events to jqGrid Pager Input Box
You can add custom events, such as blur or click, to the input boxes within jqGrid’s pager. Here’s an example of triggering the “Enter Key Press” event on blur.
var keyPressEvent = jQuery.Event('keypress');
keyPressEvent.which = 13;
keyPressEvent.keyCode = 13;
$('input.ui-pg-input').blur(function () {
$(this).trigger(keyPressEvent);
});
Making jqGrid Responsive
To make your jqGrid responsive to varying screen sizes, you can use the following JavaScript code. It resizes the width of the jqGrid to fit its parent container.
jQuery(window).bind('resize', function () {
resizeGrid('#yourGridId', '#parentContainerId');
});
jQuery(window).bind('load', function () {
resizeGrid('#yourGridId', '#parentContainerId');
});
function resizeGrid(idOfTable, responsiveParentId) {
responsiveParentId = responsiveParentId || 'body';
var pageWidth = $(responsiveParentId).width();
$(idOfTable).setGridWidth(pageWidth);
}
Resetting Row Selection in jqGrid
When you select a row in jqGrid, it remains highlighted until you click on another row. However, the highlighting is not removed when the grid loses focus. To reset row selection when the grid is out of focus, use this event handler.
$(gridId).jqGrid().focusout(function () {
$(gridId).jqGrid("resetSelection");
});
Getting the ID of Grid’s Pager (Top or Bottom)
If you have multiple jqGrids on a page, you may need to access the pager IDs. This code snippet helps you retrieve the IDs of both the top and bottom pagers of jqGrids.
var jqGrids = $('table.ui-jqgrid-btable');
if (jqGrids.length > 0) {
jqGrids.each(function (i) {
if (this.grid) {
var topPager = this.p.toppager; // ID of the top pager
var bottomPager = this.p.pager; // ID of the bottom pager
}
});
}
Getting the Count of Records
To get the count of records in a jqGrid, you can use the following code within the loadComplete
section.
var count = jQuery("#id_of_jqgrid").jqGrid('getGridParam', 'records');
Explore these jqGrid tips and tricks to make the most out of this versatile grid library and create dynamic, responsive tables in your web applications.