jqGrid - Insert custom HTML into cell

Joel Harris picture Joel Harris · Sep 11, 2013 · Viewed 8.4k times · Source

I am trying to convert a plain old html table to a jqGrid. The old table has a column containing tags which are constructed using an unordered list and list items.

Here is an example (jsfiddle) of the table before and the jqGrid after.

In this example I am using a custom formatter which uses jQuery Templates to construct DOM elements and then the formatter returns the $.html() from the resulting DOM elements.

function getTagCellContents(cellvalue) {
    var domitems=$("#jqgrid-tag-list-item").tmpl({tags: callvalue});
    return domitems.html();
}

The problem I had with this is that whitespace included in the resulting html causes the rows to be too high. This also results in awkward "Title" attributes on the cells.

Does the jqGrid provide an API for inserting DOM objects directly into the cell rather than by returning text from the custom formatter? What is the best practice for placing customized html into a jqGrid cell?

Answer

Oleg picture Oleg · Sep 11, 2013

I find your question very interesting and so +1 from me for the question.

The main understanding problem with usage of custom formatter is: it required that your callback function return HTML fragment as string. The benefit of it is good performance, which one can see mostly on the large grid. If you works with DOM elements and uses constructs like domitems.html() you will have not so good performance.

So first of all I would recommend you to use $.template function of jQuery Templates. It allows you to work with strings without usage of DOM. The answer for example describes the main idea of the modification of your code.

To fix your main problem I suggest just to remove \n and withespaces from the string. I am not RegEx professional so I suggest the following quick and dirty solution:

// Create and cache a named template function
$("#jqgrid-tag-list-item").template("cellContents");
var tmpl = $.template("cellContents"); // template function

function getTagCellContents(a) {
    var strings = tmpl($, {data: {tags: a}}); // array of strings
    return strings.join('')
               .replace(/\n+/g,'')
               .replace(/\s+/g,' ')
               .replace(/> </g,'><');
}

Your jsfiddle demo will be the following after such modification.