Ma6139735 Ma6139735 - 2 months ago 14
jQuery Question

how to merge any number of(dyanamic) table cells who has a same class?

I want to to merge table cells who has a same class using jquery,how can I do that?and here the number of cells merging is not fixes,any one have any clue?


My HTMl is Like


<table>
<tbody>
<tr>
<td>text</td>
<td class="row">text</td>
<td class="row">text</td>
<td class="row">text</td>
</tr>
<tr>
<td>text</td>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
<tr>
<td class="row">text</td>
<td class="row">text</td>
<td>text</td>
<td>text</td>
</tr>
</tbody>
</table>


am expecting output like
enter image description here

Answer

Loop the table rows, check if there are multiple .row table cells. If so, add a colspan to the first, and remove the other. Note that the text of these cells will also be removed.

$(function() {
  $('table tbody tr').each(function() {
    var colspan = $(this).find('td.row').length;
    if( colspan > 1 ) {
      $(this).find('td.row:first').attr('colspan', colspan);
      $(this).find('td.row:not(:first)').remove();
    }
  });
});
td { border: 1px solid gray; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>text</td>
      <td class="row">text</td>
      <td class="row">text</td>
      <td class="row">text</td>
    </tr>
    <tr>
      <td>text</td>
      <td>text</td>
      <td>text</td>
      <td>text</td>
    </tr>
    <tr>
      <td class="row">text</td>
      <td class="row">text</td>
      <td>text</td>
      <td>text</td>
    </tr>
  </tbody>
</table>