util.js: Tables Manipulation

DWR helps you to manipulate tables using 2 functions: dwr.util.addRows() and dwr.util.removeAllRows(). The first parameter to both is the id of the table, tbody, thead or tfoot to edit. Generally it makes sense to use tbody because it enables you to keep header and footer rows unaltered, and it is a neat work-around to some hard to track-down Internet Explorer bugs.

For details in the individual function calls, see the pages for removeAllRows() and addRows().

Demo

For simplicity in this demo we will be using a simple array of strings, but you can have anything in your array. It's most powerful when used with an array of objects.

For demo purposes, we have a table with a tbody element with id="demo1":

Unaltered Altered Button Count
var cellFuncs = [
  function(data) { return data; },
  function(data) { return data.toUpperCase(); },
  function(data) {
    return "<input type='button' value='Test' onclick='alert(\"Hi\");'/>";
  },
  function(data) { return count++; }
];

var count = 1;
dwr.util.addRows( "demo1", , cellFuncs, { escapeHtml:false });

dwr.util.removeAllRows('demo1');

The cellFuncs can return either an HTML string, or a DOM object to populate more complex controls. Generally HTML strings are a better choice because creating them is more compact, and it's a great workaround to some Internet Explorer bugs. However if a pure XHTML model ever becomes more predominant, DOM manipulation may become required.

Advanced Options

The options object is new in DWR version 1.1

We can use the options object to pass a cell creator function or a row creator function.

By default DWR provides these creator functions for you. They look something like this:

function defaultRowCreator(options) {
  return document.createElement("tr");
};

function defaultCellCreator(options) {
  return document.createElement("td");
};

The options object passed to you by DWR is the same options object that you passed in originally (containing the rowCreator and cellCreator functions). The following fields will have been altered:

But you can provide your own versions like this:

Unaltered Altered Button Count
dwr.util.addRows("demo2", , cellFuncs, {
  rowCreator:function(options) {
    var row = document.createElement("tr");
    var index = options.rowIndex * 50;
    row.style.color = "rgb(" + index + ",0,0)";
    return row;
  },
  cellCreator:function(options) {
    var td = document.createElement("td");
    var index = 255 - (options.rowIndex * 50);
    td.style.backgroundColor = "rgb(" + index + ",255,255)";
    td.style.fontWeight = "bold";
    return td;
  },
  escapeHtml:false
});

dwr.util.removeAllRows('demo2');