jureispro
jureispro

Reputation: 1402

Convert multiple tables to one table inside same DIV using jQuery

I have multiple tables inside div with same columns and I want them to convert to one table with all records from that tables.

Can it be done with jQuery?

My HTML looks like this:

<div id="multiTabels">
    <table id="table1">
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
        <tr>
            <td>Record 1</td>
            <td>Record 2</td>
        </tr>
    </table>
    <table id="table1">
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
        <tr>
            <td>Record 3</td>
            <td>Record 4</td>
        </tr>
    </table>
</div>

Upvotes: 1

Views: 1691

Answers (3)

Brijesh Bhatt
Brijesh Bhatt

Reputation: 3830

Try this:

$(document).ready(function (){
 $("#multiTabels table tr").each(function(){
   $("#newTable").append($(this)); //append to any new table
 });
});

Upvotes: 1

Josh
Josh

Reputation: 3288

Anything can be done with jQuery.

There's a really big thing to point out with my jsFiddle: I am using the thead and tbody tags. This is really important for segregating rows and is a semantic step forward in HTML. If you inspect tables in your dev console, you'll notice most browsers automatically add a tbody around all tr elements in a table now, so it's good to start doing this.

https://jsfiddle.net/wumztk45/

// This binds a hook to the document.
// If any 'click' events happen to an element with the id "cruch" this event fires.
// This event will persist even when crunch is deleted, and is good
// for when binding to elements that may not exist at the time.
$(document).on('click', "#crunch", function(event) {
        // Find our container.
    var $multiTables = $("#multiTables"),
        // Find all tables in our container.
        $tables      = $multiTables.children("table"),
        // From all tables after the first, find all <tr> elements within <tbody> elements.
        $rows        = $tables.not(":first").children("tbody").children("tr");

        // Append these rows to the first table's tbody.
        $tables.first().children("tbody").append( $rows );
        // Remove the other tables.
        $tables.not(":first").remove();

        // Disable this button.
        $(this).prop( 'disabled', true );
} );

Upvotes: 1

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this :

$(function(){
  var $firstTable = $('#multiTabels table:first');
  $('#multiTabels table:not(:first)').each(function(){
      $firstTable.append($(this).find('tr').has('td'));
      $(this).remove();
  });
});

JSfiddle Demo

Upvotes: 1

Related Questions