Set colspan / rowspan for cell

I have a table and I want to change the colspan / rowspan property of the cell at 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 are moving. Should I delete the cells above which the cell in question is located?

Can I do without removal?

I want to implement a simple spreadsheet. At the moment, I managed to select a rectangular range of cells and show a menu with the option "Merge selected cells". I would like to be able to β€œexpand” the cells, so it would be nice to cover the cells without deleting other cells.

+6
source share
2 answers

I think you need to delete the cell. Check out the following code. What I did was delete the entire row and add a new row with a new range of columns

 function setColSpan() { var table = document.getElementById('myTable'); table.deleteRow(0); var row = table.insertRow(0); var cell = row.insertCell(0); cell.innerHTML= "cell 1" cell.colSpan = 2 } 
+15
source

Cells move because this is what you say. You define the table as follows:

 <tr> <td colspan="2">cell 1</td> <td>cell 2</td> </tr> <tr> <td>cell 3</td> <td>cell 4</td> </tr> 

So, the shift that you see, I expect.

If you want to merge cells, you will need to take the contents of all merged cells, merge them into one cell and delete the rest. For a trivial example, it would look like this:

 function setColSpan() { var myTable = document.getElementById('myTable'); var cell2html = myTable.rows[0].cells[1].innerHTML; myTable.rows[0].deleteCell(1); myTable.rows[0].cells[0].innerHTML = myTable.rows[0].cells[0].innerHTML + ' ' + cell2html; myTable.rows[0].cells[0].colSpan = 2; } 

However, a more reliable solution is a complex process. Especially if you want the ability to unfold. You would need to somehow store the information about the old cell structure ... maybe something like <span class="oldCell">cell 2</span> around the merged data? And then checking for the existence of "oldCell" covers when it does not work? But then you have to save this information with the help of user rights. And find out what it means to merge rows and columns. And also find out what this means for overlapping mergers.

0
source

All Articles