WEBDOOD.COM

HTML

Javascript HTML Tables EnsureMinimumNumberOfRows

by on Apr.20, 2010, under HTML, Javascript, Software Development

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 contents of the cells, but rather the nodes themselves and their classnames (by way of cloneNode(false).

///////////////////////////////////////////////////////////////////////////////
// EnsureMinimumNumberOfRows(element, params)  
// ==========================================    
// Ensures a table will have minimum number of visible rows.   
// Supported params are:  
//   numberOfRows - gives the minimum number of rows that will appear 
//                          default minimumNumberOfRows is 10
//   rowHeight - height, in pixels for added rows. Default is 30px
//  *NOTE: Does not support empty tables 
////////////////////////////////////////////////////////////////////////////////
function EnsureMinimumNumberOfRows(element, params) { 
  var minimumNumberOfRows  = params.numberOfRows || 10,       
       rowHeight            = params.rowHeight    || 30,        
  // Get the first element as $(element).select returns an array 
  // *Note this is a rare use of the Prototype Library on my part.
  oTable = $(element).select('div.resultList table')[0],   
  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

Leave a Comment :, , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

  • A List Apart
  • Dive into HTML5
  • Javascript: The Good Parts
  • QuirksMode.org