Search code examples
javascriptjqueryhtmlhtml-tabletablesorter

How to make a html-table sortable while not sorting specific rows?


I have a html-table, that has a header, that is supposed to be clickable to sort the rows on the clicked column. The tricky part here is, that there are some rows in the table, that shouldn't be sorted and the rows, that belong to that specific row should remain under that row. Here is some code so you get what I'm talking about.

<table>
    <thead>
        <tr>
            <th>User</th>
            <th>Item</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th colspan="5" style="text-align:left;">Peter</th>
        </tr>
        <tr>
            <td></td>
            <td>Apple</td>
            <td>10</td>

        </tr>
        <tr>
            <td></td>
            <td>Pineapple</td>
            <td>15</td>

        </tr>
        <tr>
            <th colspan="5" style="text-align:left;">Stan</th>
        </tr>
        <tr>
            <td></td>
            <td>Banana</td>
            <td>7</td>
        </tr>
        <tr>
            <td></td>
            <td>Orange</td>
            <td>10</td>
        </tr>
    </tbody>
</table>

So if I click for example on the Item-Header, the Apple + Pineapple rows should remain between the Peter and the Stan row while being sorted. If I click on the User-Header, Peter and Stan should be sorted, while the Items Apple + Pineapple remain under the Peter row and the Banana and Orange Items remain under the Stan row ... I hope you get what I mean. I have already tried it with the jquery tablesorter-plugin but I couldn't find any solution that was working for me.


Solution

  • You'll need to enclose each block of rows in a separate tbody.

    Then clicking on User will only sort the tbodys, and clicking on the other ths will sort each tbody separately.

    EDIT

    The table should look like this:

    <table>
      <thead>
        <tr>
            <th>User</th>
            <th>Item</th>
            <th>Price</th>
        </tr>
      </thead>
      <tbody>
        <tr>
            <th colspan="5" style="text-align:left;">Peter</th>
        </tr>
        <tr>
            <td></td>
            <td>Apple</td>
            <td>10</td>
    
        </tr>
        <tr>
            <td></td>
            <td>Pineapple</td>
            <td>15</td>
    
        </tr>
      </tbody>
      <tbody>
        <tr>
            <th colspan="5" style="text-align:left;">Stan</th>
        </tr>
        <tr>
            <td></td>
            <td>Banana</td>
            <td>7</td>
        </tr>
        <tr>
            <td></td>
            <td>Orange</td>
            <td>10</td>
        </tr>
      </tbody>