nehel nehel - 3 months ago 6
jQuery Question

set dynamically colspan jquery

I'm setting

table rows
dynamically. When there are more than
4
rows,
table
is too big and I have to cut it.

The idea is, when there is
5th row
coming, it goes into
second column
of
previous row
, so there are still
4
rows, where
last row
has
2 columns
. And then I'm trying to set
colspan="2"
for the
rows
that have
1 col
.

But the thing is it doesn't want to work. I'm stuck with that for 2 days now and i can't find any idea for it... Would really love to hear any tips from You. Thanks in advance.

I've tried also setting
colspan="2"
into
generateTD() function
- no effects so far.



var container = document.getElementById('container');
function generateTD(){
var output = '';
for(var i=1; i<7; i++){
output += '<tr>';
if(i<5){
output += '<td class="merged-col">Row#'+[i]+'</td>';
if(i>=4){
output += '<td>Row#'+[i]+'</td>';
}
}
output += '</tr>';
}
container.innerHTML = output;
}

generateTD();
$('.merged-col').attr('colspan', 2);

td{
border: 1px solid black;
padding: 4px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="container"></table>




Answer

Just calculate rows and columns.

var container = document.getElementById('container');
function generateTD(){
  var output = '';
  for(var i=1; i<7; i++){
    output += '<tr>';
    if(i < 4){
      output += '<td class="merged-col">Row#'+[i]+'</td>';
      //if(i>=4){
      //  output += '<td>Row#'+[i]+'</td>';
      //}
    }
    else{
       output += '<td>Row#'+[i]+'</td>';
       output += '<td>Row#'+[i]+'</td>';
    }
    output += '</tr>';
   }
  container.innerHTML = output;
}

generateTD();
$('.merged-col').attr('colspan', 2);
td{
  border: 1px solid black;
  padding: 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="container"></table>