Reputation: 5670
I have an HTML table in my page. like this
<table class="table table-bordered table-responsive">
<thead>
<tr class="tablewhite">
<th> No</th>
<th>Options</th>
<th>Dash</th>
<th>mm</th>
<th>Inch</th>
<th>mm</th>
<th>mm</th>
</tr>
</thead>
<tbody>
<tr class="tablecontentwhite">
<td>19904408</td>
<td>S/G</td>
<td>-4</td>
<td>4.4</td>
<td>5/16"</td>
<td>7.9</td>
<td>20.0</td>
</tr>
<tr class="tablecontentblue">
<td> Material: Acidproof Stainless Steel with bronze inserted thread.</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="tablecontentwhite">
<td> - K=Clevis Pin Treaded w/Nut, G=Clevis Pin w/G-ring</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
There is a chance that last three rows of the table may differ in structure. Like I show above, last two rows have text in only first column. If only first column of the column have text in it, I want to give it maximum width. In this case add colspan="7"
to the column with text and remove all empty columns in that row. Desired output will be like this
<table class="table table-bordered table-responsive">
<thead>
<tr class="tablewhite">
<th> No</th>
<th>Options</th>
<th>Dash</th>
<th>mm</th>
<th>Inch</th>
<th>mm</th>
<th>mm</th>
</tr>
</thead>
<tbody>
<tr class="tablecontentwhite">
<td>19904408</td>
<td>S/G</td>
<td>-4</td>
<td>4.4</td>
<td>5/16"</td>
<td>7.9</td>
<td>20.0</td>
</tr>
<tr class="tablecontentblue">
<td colspan="7"> Material: Acidproof Stainless Steel with bronze inserted thread.</td>
</tr>
<tr class="tablecontentwhite">
<td colspan="7"> - K=Clevis Pin Treaded w/Nut, G=Clevis Pin w/G-ring</td>
</tr>
</tbody>
</table>
Can any one point out the correct way to achieve this?
Upvotes: 1
Views: 1017
Reputation: 3580
just giving an idea. you can try this. works with next empty elements.
$('tr').each(function(index, tr) {
var previous = false;
$(tr).find('td').each(function(index1, td) {
if(td.innerText == "") {
if(previous) {
var p = $(previous);
if(!p.attr('colspan')) {
p.attr('colspan', 1);
}
p.attr('colspan', parseInt(p.attr('colspan'))+1);
$(td).remove();
}
} else {
previous = td;
}
});
});
you can also simply write like this
$('tr').each(function(index, tr) {
$(this).find('td:not(:empty)').attr('colspan', $(this).find('td:empty').length);
$(this).find('td:empty').remove();
});
for splitting cells length you can change the second line
$(this).find('td:not(:empty)').attr('colspan', $(this).find('td:empty').length/$(this).find('td:not(:empty)'));
Upvotes: 2