Short answer on your question could be: jqGrid provide no method which allows to change column width after grid have created. In such cases I remind well known aphorism of Kozma Prutkov: “Who prevents you invent gunpowder waterproof?”. It means about the following: if something not exists it can be still invented. So I wrote such method based on the solution suggested in the answer where I suggested to call internal method dragEnd
to resize grid’s column.
The demo demonstrate the usage of new method. The demo allows to choose some column of the grid and then to change the width to new value which you specify:
The code of new method you can find below
$.jgrid.extend({
setColWidth: function (iCol, newWidth, adjustGridWidth) {
return this.each(function () {
var $self = $(this), grid = this.grid, p = this.p, colName, colModel = p.colModel, i, nCol;
if (typeof iCol === "string") {
// the first parametrer is column name instead of index
colName = iCol;
for (i = 0, nCol = colModel.length; i < nCol; i++) {
if (colModel[i].name === colName) {
iCol = i;
break;
}
}
if (i >= nCol) {
return; // error: non-existing column name specified as the first parameter
}
} else if (typeof iCol !== "number") {
return; // error: wrong parameters
}
grid.resizing = { idx: iCol };
grid.headers[iCol].newWidth = newWidth;
grid.newWidth = p.tblwidth + newWidth - grid.headers[iCol].width;
grid.dragEnd(); // adjust column width
if (adjustGridWidth !== false) {
$self.jqGrid("setGridWidth", grid.newWidth, false); // adjust grid width too
}
});
}
});
You can include the method in your project and then use setColWidth
method. The first parameter of the method is either the column index or the column name. The second parameter is a number which specify new value of the width on the column. The third parameter is optional. If it’s not specified then the width of the grid will be automatically adjusted corresponds to the changing of the column width. So the grid will have no scroll bars if it hasn’t before changing the column width. If you want to hold the original grid width you should specify false
as the third parameter of setColWidth
method.
UPDATED: The latest (updated) version of setColWidth
can be downloaded from github. The new free version of jqGrid which is developing currently here includes the method as in the basis module of jqGrid. So if you use jquery.jqGrid.min.js
, jquery.jqGrid.min.map
and jquery.jqGrid.src.js
from here then you don’t need include jQuery.jqGrid.autoWidthColumns.js with setColWidth
as plugin.
UPDATED 2: I modified the above code to corresponds the latest version of setColWidth
which I published to github.
UPDATEd 3: The method setColWidth
is included in free jqGrid fork of jqGrid, which I develop since the end of 2014. It includes many other new features like extending the width of the column based on the width of content of the column. See the wiki article for more details.