Saturday, January 01, 2011

Moving a HTML Table Row

No comments:
This has probably been done a million times before but i thought I would record my home-brew effort for posterity. The point of the following Javascript is to change the sequence in which Table Rows display using Javascript - this could be extended via AJAX calls to write back the new sequence to the data store but is beyond the scope of what I'm currently trying to achieve!

This method should be fairly generic and should work for any table with any number of columns and rows!

The Javascript function:
<script language="javascript" type="text/javascript">
function move(direction, tableCell) {
// Prepare variables to make code easier to read!
var table = tableCell.parentNode.parentNode;
var rowCount = table.rows.length;
var currentRow = tableCell.parentNode;
var currentRowIndex = currentRow.rowIndex;
// Disallow movement past bounds of table rows!
if (((currentRowIndex == 0) && (direction == 1)) || ((currentRowIndex == (rowCount - 1)) && (direction == 0))) return false;
// Find the Current Row's Sibling we're swapping position with
var newRowIndex = (direction == 0) ? currentRowIndex + 1 : currentRowIndex - 1;
var currentRowSibling = table.rows[newRowIndex];
// loop here foreach cell
for (var cellIndex = 0; cellIndex < currentRow.cells.length; cellIndex++) {
var currentRowSiblingCellHTML = currentRowSibling.cells[cellIndex].innerHTML;
currentRowSibling.cells[cellIndex].innerHTML = currentRow.cells[cellIndex].innerHTML;
currentRow.cells[cellIndex].innerHTML = currentRowSiblingCellHTML;
}
}
</script>
Read More