locked
convert html table column to row RRS feed

  • Question

  • User-1634604574 posted

    i have this table 

    colour

    red       green     blue    black

    size

    small    large     x-large

    weight

    A1         A2

    i want to convert to this shape

    colour

    red         green     

    blue        black

    size

    small        large   

     x-large

    weight

    A1         A2

    Wednesday, January 23, 2019 7:37 PM

Answers

  • User839733648 posted

    Hi  zhyanadil.it@gmail.com,

    According to your description, I've made a sample on my side.

    The key point is to find the row which has column more than two and move it to next line.

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script>
            $(function () {
                $("#btn").click(function () {
                    var rowlen = $("#tbl1 tr").length;
                    for (i = 0; i < rowlen; i++) {
                        var collen = $("#tbl1 tr").eq(i).children().length;
                        if (collen > 2) {
                            $("#tbl1 tr:eq(" + i + ")").after("<tr></tr>").after($("#tbl1 tr:eq(" + i + ") td:gt(1)").clone());
                            $("#tbl1 tr:eq(" + i + ") td:gt(1)").remove();
                        }
    
                    }
                })
    
            })
        </script>
        <style>
            #btn, #tbl2container {
                margin-top: 10px;
            }
    
            td {
                padding: 5px;
                border: 1px dotted gray;
            }
        </style>
    </head>
    <body>
        <div id="tbl1container">
            <table id="tbl1">
                <tr>
                    <td>colour</td>
                </tr>
                <tr>
                    <td>red</td>
                    <td>green</td>
                    <td>blue</td>
                    <td>black</td>
                </tr>
                <tr>
                    <td>size</td>
                </tr>
                <tr>
                    <td>samll</td>
                    <td>large</td>
                    <td>x-large</td>
                </tr>
                <tr>
                    <td>weight</td>
                </tr>
                <tr>
                    <td>A1</td>
                    <td>A2</td>
                </tr>
            </table>
        </div>
        <button id="btn">Convert Table</button>
    </body>
    </html>

    result:

    Best Regards,

    Jenifer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 24, 2019 7:18 AM