Entry
How do I swap to cells in a table?
Sep 9th, 2004 04:12
Martin Honnen,
Using the W3C DOM, here in particular the createElement method of the
document to create a dummy cell and the replaceChild method of a node,
the following example has a function named swapCells to swap cells and
some code to provide a test case for that function:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>swapping table cells</title>
<script type="text/javascript">
function swapCells (cell1, cell2) {
var dummyCell;
if (document.createElement &&
(dummyCell = document.createElement('td'))) {
cell1.parentNode.replaceChild(dummyCell, cell1);
cell2.parentNode.replaceChild(cell1, cell2);
dummyCell.parentNode.replaceChild(cell2, dummyCell);
}
}
</script>
<script type="text/javascript">
var rows, cols;
function createRandomTable () {
rows = Math.floor(Math.random() * 10 + 5);
cols = Math.floor(Math.random() * 10 + 5);
var html = '';
html += '<table id="aTable" border="1">\r\n';
html += '<tbody>\r\n';
for (var r = 0; r < rows; r++) {
html += '<tr>\r\n';
for (var c = 0; c < cols; c++) {
html += '<td>cell ' + r + ', ' + c + '<\/td>\r\n';
}
html += '<\/tr>\r\n';
}
html += '<\/tbody>\r\n';
html += '<\/table>\r\n';
document.write(html);
}
function createSelect (selectName, upperBound) {
var html = '';
html += '<select name="' + selectName + '">\r\n';
for (var r = 0; r < upperBound; r++) {
html += '<option value="' + r + '">' + r + '<\/option>\r\n';
}
html += '<\/select>\r\n';
document.write(html);
}
function doCellSwap (form, tableId) {
var table;
if (document.getElementById &&
(table = document.getElementById(tableId))) {
var rowIndex1 = form.elements.rowIndex1.value;
var cellIndex1 = form.elements.cellIndex1.value;
var rowIndex2 = form.elements.rowIndex2.value;
var cellIndex2 = form.elements.cellIndex2.value;
if (table.rows) {
var cell1 = table.rows[rowIndex1].cells[cellIndex1];
var cell2 = table.rows[rowIndex2].cells[cellIndex2];
swapCells(cell1, cell2);
}
}
}
</script>
</head>
<body>
<div>
<script type="text/javascript">
createRandomTable();
</script>
</div>
<form action="" onsubmit="return false;">
<p>
<label>Select rowIndex of first cell:
<script type="text/javascript">
createSelect('rowIndex1', rows);
</script>
</label>
<label>select cellIndex of first cell:
<script type="text/javascript">
createSelect('cellIndex1', cols);
</script>
</label>
</p>
<p>
<label>Select rowIndex of second cell:
<script type="text/javascript">
createSelect('rowIndex2', rows);
</script>
</label>
<label>select cellIndex of second cell:
<script type="text/javascript">
createSelect('cellIndex2', cols);
</script>
</label>
</p>
<p>
<input type="button" value="swap selected cells"
onclick="doCellSwap(this.form, 'aTable');">
</p>
</form>
</body>
</html>