jqgrid column width auto

Mark picture Mark · Feb 19, 2014 · Viewed 10.1k times · Source

Is there a way that the column width of jqgrid change dynamically according to the content of that column? I used shrinkToFit and autoWidth but non of them worked for me. I use jqgrid 4.5.2. I have searched and read the other questions but those didn't work for me. Maybe there is a widget to do that. I will be thankful if you help me.

Answer

pphillips001 picture pphillips001 · Sep 10, 2014

Here's how I implement jqGrid column width based on column content. Add this to the gridComplete event.

$(this).parent().append('<span id="widthTest" />');

gridName = this.id;

$('#gbox_' + gridName + ' .ui-jqgrid-htable,#' + gridName).css('width', 'inherit');
$('#' + gridName).parent().css('width', 'inherit');

var columnNames = $("#" + gridName).jqGrid('getGridParam', 'colModel');
var thisWidth;

// Loop through Cols
for (var itm = 0, itmCount = columnNames.length; itm < itmCount; itm++) {

     var curObj = $('[aria-describedby=' + gridName + '_' + columnNames[itm].name + ']');

     var thisCell = $('#' + gridName + '_' + columnNames[itm].name + ' div');
     $('#widthTest').html(thisCell.text()).css({
           'font-family': thisCell.css('font-family'),
           'font-size': thisCell.css('font-size'),
           'font-weight': thisCell.css('font-weight')
     });
     var maxWidth = Width = $('#widthTest').width() + 24;                    
     //var maxWidth = 0;                      

     // Loop through Rows
     for (var itm2 = 0, itm2Count = curObj.length; itm2 < itm2Count; itm2++) {
          var thisCell = $(curObj[itm2]);

          $('#widthTest').html(thisCell.html()).css({
               'font-family': thisCell.css('font-family'),
               'font-size': thisCell.css('font-size'),
               'font-weight': thisCell.css('font-weight')
          });

          thisWidth = $('#widthTest').width();
          if (thisWidth > maxWidth) maxWidth = thisWidth;                        
     }                    

     $('#' + gridName + ' .jqgfirstrow td:eq(' + itm + '), #' + gridName + '_' + columnNames[itm].name).width(maxWidth).css('min-width', maxWidth);

 }

 $('#widthTest').remove();

A working example:

http://jsfiddle.net/Ba5yK/17/

Hope this helps,

Paul