skip to Main Content

I am going to generate a table with td colspan.

for(let x = 0; x < rows; x++){
  table += "<tr>";
  for(let y=0; y < cols; y++){
    if(x == 1 && y == 2) {
      table += `<td colspan="3">${y}</td>`;
    } else {
      table += `<td>${y}</td>`;
    } 
  }
  table += "</tr>";
}

The problem is when I merge cells using colspan, there is an excess of columns.

https://jsfiddle.net/jL8dq1rg/

How can remove excess column (5,6) so that the columns will be even?

Note: The x & y values are dynamic so as with the colspan. Meaning, any row could have a colspan.

enter image description here

3

Answers


  1. for(let x = 0; x < rows; x++){
      table += "<tr>";
      for(let y=0; y < cols; y++){
        if(x == 1 && y == 2) {
          table += `<td colspan="3">${y}</td>`;
          y+=2 //y+2 End cycle early
        } else {
          table += `<td>${y}</td>`;
        } 
      }
      table += "</tr>";
    }
    
    Login or Signup to reply.
  2. You may for example skip the columns counter when the cell spanning is encountered.

    But I see in the meanwhile a similar answer was already delivered.

    var table = '';
    const rows = 5;
    const cols = 6;
    
    for(let x = 0; x < rows; x++){
      table += "<tr>";
      for(let y=0; y < cols; y++){
        //if 2nd row and 3rd column,
        if(x == 1 && y == 2) {
          //set the cell data to span 3 columns
          table += `<td colspan="3">${y}</td>`;
          y+=2; //<---- increment the cols counter skipping the cols this cell is spanning across
        } else {
          table += `<td>${y}</td>`;
        } 
      }
      table += "</tr>";
    }
    
    document.getElementById('target')
      .innerHTML = table;
    table td{
      border: solid;
    }
    <table id="target"></table>
    Login or Signup to reply.
  3. You could work with the "y" variable of your for-loop and add +2 to your variable whenever you add a colspan.

    const rows = 5;
    const cols = 7;
    
    let table = "<table border='1'>";
    for(let x = 0; x < rows; x++){
        table += "<tr>";
      for(let y=0; y < cols; y++){
        if(x == 1 && y == 2) {
          table += `<td colspan="3">${y}</td>`;
    
          y += 2
    
        } else {
            table += `<td>${y}</td>`;
        } 
      }
      table += "</tr>";
    }
    
    table += "</table>";
    
    document.getElementById('app').innerHTML = table;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search