warvariuc warvariuc - 4 months ago 28
Javascript Question

Set colspan/rowspan for a cell

I have a table and i want to change

colspan
/
rowspan
property of a cell on runtime. Here is an example:

<html>
<head>
<script type="text/javascript">
function setColSpan() {
document.getElementById('myTable').rows[0].cells[0].colSpan = 2
}
</script>
</head>

<body>
<table id="myTable" border="1">
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</table>
<form>
<input type="button" onclick="setColSpan()" value="Change colspan">
</form>
</body>

</html>


My problem is that the cells shift. Am i supposed to remove the cells over which the cell in question spans?

I can i do without removing?

I want to implement a simple spreadsheet. For now i managed to be able to select a rectangular range of cells and show a menu with a "Merge selected cells" option. I would like to be able to "unmerge" cells, so it would be good to span cells without having to remove other cells.

Answer

I think you need to delete the cell. Check with following code. What i did was removed the entire row and added new row with new column span

 function setColSpan() {
                document.getElementById('myTable').deleteRow(0);
                var row = document.getElementById('myTable').insertRow(0);
                 row.insertCell(0);
                document.getElementById('myTable').rows[0].cells[0].innerHTML= "cell 1"
                document.getElementById('myTable').rows[0].cells[0].colSpan = 2
            }