tabs

Thursday, October 31, 2013

How to merge or combine two tables into one?

In this post I am going to explain how to merge two tables of your web page into a single table using jQuery. This may not be a frequent practice in our daily applications but let us make use of our programming skills to meet each and every requirement according to the situation.
What we need to do here is,
  1. Create two tables in your Webform.
  2. Output is shortened to a single table with the two tables merged.
Let the following be your HTML code:
merge.aspx:
<form id="Form1" onsubmit="return merge();" runat="server">
    <div>
        <table class="primaryTable" style="border1px solid grey;">
            <thead>
                <tr>
                    <td>Name</td>
                    <td>Age</td>
                </tr>
            </thead>
            <tr>
                <td>T1-ROW1-Name</td>
                <td>T1-ROW1-Age</td>
            </tr>
            <tr>
                <td>T1-ROW2-Name </td>
                <td>T1-ROW2-Age </td>
            </tr>
        </table>
        <table class="secondaryTable">
            <tr>
                <td>T2-ROW1-Name</td>
                <td>T2-ROW1-Age</td>
            </tr>
            <tr>
                <td>T2-ROW2-Name</td>
                <td>T2-ROW2-Age</td>
            </tr>
        </table>
    </div>
</form>
 
The above code just creates two tables with the first table having id=’primaryTable’. And the second table with id=’secondaryTable’.
Now we will use simple jQuery to merge these two tables in to one.The logic we implement here is we merge the first table’s last child of its parent element with the body of the second table.
Following is my JavaScript file.
merge.js


$(document).ready(function () {
    $(".primaryTable > tbody:last").append($(".secondaryTable > tbody").html());
    $(".secondaryTable").remove();
});
 

 That’s all ,the two tables will be merged to a single table with small piece of jQuery code. Hope it helps you. Feel free to suggest and post your valuable comments.

No comments:

Post a Comment