3

I have a table where I want to insert a new row with a different colspan then the original table. Here is part of my code:

var table = document.getElementById("eTable");    
var rowIndex = document.getElementById(ID).rowIndex;
var row = table.insertRow(rowIndex + 1);
var cell = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);

My original table has 5 columns, but I want to merge cell1,cell2, and cell3. How do I do that?

barbsan
  • 3,418
  • 11
  • 21
  • 28
TheAsker
  • 55
  • 1
  • 9
  • "_row with a different colspan_" There's no such a thing in HTMLTables, `rowspan` and `colspan` are properties of `td` elements. But you can merge the cells. Add `cell.colspan = 3;` and omit `cell3` and `cell4`. – Teemu Nov 23 '18 at 13:19
  • how would you do that ? – TheAsker Nov 23 '18 at 13:25
  • ??How?? Exactly like in my comment ... – Teemu Nov 23 '18 at 13:29
  • @TheAsker build table using string like `var tableBuild = '` //loop your data here as required with col or rowspan`
    '` . Refer this solution https://stackoverflow.com/a/8749347/4425004
    – Pranesh Janarthanan Nov 23 '18 at 13:35

2 Answers2

5

It's possible to set the colspan for a column and skip some other columns. Based on your code (added second row):

var table = document.getElementById("eTable");    
var rowIndex = document.getElementById("ID").rowIndex;
var row = table.insertRow(rowIndex + 1);
var cell = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
row = table.insertRow(rowIndex);
cell = row.insertCell(0);
cell1 = row.insertCell(1);
cell1.colSpan = "3";
cell2 = row.insertCell(2);
table { border: 1px solid #000; width: 100%; }
table tr { }
table td { border: 1px solid red; height: 20px;}
<input type="hidden" id="ID" value=0 />
<table id="eTable">
</table>

Run the snippet or if you prefer, see this fiddle

haldo
  • 14,512
  • 5
  • 46
  • 52
0

Try below javascript code.

var cell2 = row.insertCell(2);
cell2.id = "myTd";
document.getElementById("myTd").colSpan = "3"
Yogesh Patel
  • 818
  • 2
  • 12
  • 26