Tuesday, April 20, 2010

EnsureMinimumNumberOfRows

Here I present a useful function called "EnsureMinimumNumberOfRows".

This function operates on a table and effectively clones the last row in the table a given number of times to ensure that a minimum number of rows exist within the table. it does not clone the contetns of the cells, but rather the nodes themselves and their classnames (by way of cloneNode(false).


////////////////////////////////////////////////////////////////////////////////
// EnsureMinimumNumberOfRows(element, params) - ensures a table will have a minimum
// ========================================== number of visible rows.
// Supported params are:
// numberOfRows - gives the minimum number of rows that will appear
// rowHeight - height, in pixels for added rows
// *NOTE: Does not support empty tables
////////////////////////////////////////////////////////////////////////////////
function EnsureMinimumNumberOfRows(element, params) {
var minimumNumberOfRows = params.numberOfRows || 10, // default minimumNumberOfRows is 10
rowHeight = params.rowHeight || 30, // default rowHeight (for new rows) is 30px
oTable = $(element).select('div.resultList table')[0], // Get the first element as $(element).select returns an array
numberOfRowsToInsert = minimumNumberOfRows - oTable.rows.length + 1;

if (numberOfRowsToInsert > 0) {
var clonedRow = oTable.rows[ oTable.rows.length - 1 ]
clonedCells = clonedRow.getElementsByTagName('td');
for (var i=0;i<numberOfRowsToInsert;i++) {
var oRow = document.createElement("TR");
for (j=0;j<clonedCells.length;j++) {
var oCell = clonedCells[j].cloneNode(false);
oCell.style.height = rowHeight + "px";
oCell.appendChild( document.createTextNode("\u00a0") );
oRow.appendChild(oCell);
}
oTable.appendChild( oRow );
}
}
}

Shannon Norrell


Now posted on GitHub

No comments: