1

I want to group the table header according to the same content.

 <table id="tblSample" border="1" >
    <tbody>
        <tr><th>Group#1</th><th>Group#1</th><th>Group#1</th><th>Group#21</th></tr>
        <tr><th>Sub-Group#1</th><th>Sub-Group#1</th><th>Sub-Group#2</th><th>Sub-Group#2</th></tr>
        <tr><td>1</td><td>2</td><td>3</td><td>4</td>   </tr>       
    </tbody>
</table>

Here I want to merge the columns Group#1 as asingle column and Sub-Group#1 as well as. Any Idea? I tried a code but it doesn't worked. Here is my demo : http://jsfiddle.net/L3ab1edw/1/

expected output: ------------------------------------------------------- Group#1 | Group#2 ------------------------|--------------------------------- Sub-Group#1 | Sub-Group#2 -----------|------------|------------|--------------------- 1 |2 |3 |4

$(document).ready(function () {
    $('#tblSample').each(function () {
        var Column_number_to_Merge = 1;
          var Previous_TH = null;
        var i = 1;
        $("thead",this).find('tr').each(function () {
                var Current_th = $(this).find('th:nth-child(' + Column_number_to_Merge + ')');

            if (Previous_TH == null) {

                Previous_TH = Current_th;
                i = 1;
            } 
            else if (Current_th.text() == Previous_TH.text()) {

                Current_th.remove();

                Previous_TH.attr('colspan', i + 1);
                i = i + 1;
            } 
            else {

                Previous_TH = Current_th;
                i = 1;
            }
        });
    });
});
1
  • If I understand correctly do you want something like that in the end... <table id="tblSample" border="1" > <tbody> <tr><th>Group#1</th><th>Group#2</th></tr> <tr><th>Sub-Group#1</th><th>Sub-Group#2</th></tr> <tr><td>1</td><td>4</td></tr> </tbody> </table> Commented Jul 1, 2015 at 11:07

1 Answer 1

1

Use colspan:

 <table id="tblSample" border="1" >
    <tbody>
        <tr><th colspan="3">Group#1</th><th>Group#21</th></tr>
        <tr><th>Sub-Group#1</th><th>Sub-Group#1</th><th>Sub-Group#2</th><th>Sub-Group#2</th></tr>
        <tr><td>1</td><td>2</td><td>3</td><td>4</td>   </tr>       
    </tbody>
</table>

I don't understand why you need a jQuery to do such a simple task, but here you go:

$("#tblSample")
    .find("tbody tr:first-child")
    .html('<th colspan="3">Group#1</th><th>Group#21</th>');
Sign up to request clarification or add additional context in comments.

2 Comments

Actually I want a jQuery function to merge it.
@Rose Added jQuery solution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.