Ramesh
Ramesh

Reputation: 113

Merge table cells using jQuery

I need to merge table cells for a particular column using jQuery.

Input table:
enter image description here

Result table:
enter image description here

How can I do this?

Upvotes: 3

Views: 6546

Answers (2)

shyammakwana.me
shyammakwana.me

Reputation: 5752

LIVE DEMO

You can give class to third row and then using below jQuery you can merge cells.

HTML & jQuery

$('.third-row td:eq(2)').attr('rowspan','2').parent().next().find('td:eq(2)').remove()
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>

<table border="1" width="100%">
<tr>
	<td>1</td>
	<td>1</td>
	<td>1</td>
	<td>1</td>
</tr><tr class="third-row">
	<td>1</td>
	<td >2</td>
	<td>3</td>
	<td>4</td>
</tr><tr>
	<td>1</td>
  <td>2</td>
	
	<td>5</td>
	<td>6</td>
</tr></table>

Update :

Without adding class to row you can achieve this by jQuery's eq() function.

Upvotes: 3

Yerko Palma
Yerko Palma

Reputation: 12329

I guess this is what you want.

$(document).ready(function(){
      
      var el = $("tr td:last-child");
      for(var i = 0; i < el.length; i++){
        if (el[i].innerHTML == el[i+1].innerHTML){
          el[i].setAttribute("rowspan","2");
          el[i+1].parentElement.removeChild(el[i+1])
        }
      }  
      
      
    });
td, th, tr, table {
      border: solid 1px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

    <table corder="1" class="reference" style="width:100%">
    <tbody><tr>
    	<th>Number</th>
    	<th>First Name</th>
    	<th>Last Name</th>		
    	<th>Points</th>
    </tr>
    <tr>
    	<td>1</td>
    	<td>Eve</td>
    	<td>Jackson</td>		
    	<td>94</td>
    </tr>
    <tr>
    	<td>2</td>
    	<td>John</td>
    	<td>Doe</td>		
    	<td>80</td>
    </tr>
    <tr>
    	<td>3</td>
    	<td>Adam</td>
    	<td>Johnson</td>		
    	<td>80</td>
    </tr>
    <tr>
    	<td>4</td>
    	<td>Jill</td>
    	<td>Smith</td>		
    	<td>50</td>
    </tr>
    </tbody></table>

Upvotes: 2

Related Questions