How to adjust the column width of jqgrid AFTER the data is loaded?
Asked Answered
A

1

8

My ultimate goal is to have jqgrid to auto-set the column width according to the data content. As part of the path to go there, I need to be able to set the column width AFTER the data is loaded by which time I would know the maximum width of each column. But once I know the maximum width of a column, how can I set the width of each column in the "loadComplete" event and have the grid refresh with the new width of each column? Most of the posts I've found on the net are regarding the grid's overall width. What I want is to set each individual column's width and have the horizontal scrollbar appear automatically if the total width is too long.

Update: After seeing Oleg's awesome demo, I ended up coding this in the dqGrid (4.5.4) itself. Here's what I did:

Locate the function

addJSONData = function(data,t, rcnt, more, adjust) {

then locate within this function

            for (j=0;j<rowReader.length;j++) {
                v = $.jgrid.getAccessor(cur,rowReader[j]);
                rd[ts.p.colModel[j+gi+si+ni].name] = v;
                rowData.push(addCell(idr, v, j + gi + si + ni, i + rcnt, cur, rd));

                // my addtion: stores the largest header size
                var newWidth = v.length * 6; 
                if (ts.grid.headers[j].width < newWidth) {
                    ts.grid.headers[j].width = newWidth;
                }
            }

Then right before the end } of this function, add the following

        // my addition: invoke the resizing logic
        for (j = 0; j < rowReader.length; j++) {
            ts.grid.resizing = { idx: j };
            ts.grid.dragEnd();
        }

After that, the grid will adjust the width of each column according to the content. One thing I still need help on is how to calculate preciously the new width. My current hard-coded calculation

var newWidth = v.length * 6;

is obviously not very scalable.

Ambriz answered 15/11, 2013 at 23:21 Comment(0)
P
18

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:

enter image description here

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.

Periphrastic answered 17/11, 2013 at 12:28 Comment(8)
Thanks for the cool demo. See my "update" on what I ended up doing. Any idea on how to calculate the exact width in pixels that I should return?Ambriz
@dreamfly: You are welcome! I find "update" a little strange. First of all it's new question (the original was "How to adjust the column width of jqGrid AFTER the data is loaded?"). Seconds I don't recommend to change source code of jqGrid if it's really required. Instead of that you can use loadComplete or beforeProcessing. Now about your main question: I think that you can wrap cell content inside of <span>...</span>. After that you can use jQuery.width to compute the exact width in pixel of every <span> and so of every text in the cell. Finally you can use setColWidth.Periphrastic
I am well aware of the pitfall of changing the source code. This is just a proof of concept on how difficult it is to implement this in my opinion a rather simple but very useful feature. especially the simple HTML table does that natively. Of course efficiency was also achieved without re-processing the data.Ambriz
It came full cycle! I Just tried the free jqgrid with the {autoResizable: true } on every column and it worked. However the performance on IE11 is rather slow with just 500 rows and 13 columns of data. It seems it's running the autoResize logic on every scroll action.Ambriz
@dreamfly. Could you provide the demo which uses non-minimized the latest version of free jGrid? Try the demo and make double-click between column headers. Moreover I not full understand why you want to use 500 rows without paging? The monitor is unable to display 500 rows (maximally probably 35). In the way you reduce performance of the grid in 100 times or more. the demo with 40000 rows works quickly.Periphrastic
I tried to use this, but it doesn't seem to work with grouped headers. Is there a resolution that you have to make it work with other examples?Kattiekatuscha
@ThomasMondelli: It's difficult to guess, which problem you have if you don't provide and code or the demo. the demo for example, groups and sort 4000 rows and another one grouped 40000 rows.Periphrastic
Sorry, that is data grouping, I meant header grouping. The grouped headers do not change width. I will work on a demo in the morning.Kattiekatuscha

© 2022 - 2024 — McMap. All rights reserved.