skip to Main Content

I am showing a HTML table using the jQuery Mottie tablesorter. I would like the rows with a "v" in one of its columns to be formatted with a certain (given) background color, which is retained after sorting the table. How can this be achieved?

    <table id="tablesorter_Table" class="tablesorter">
    <thead>
    <tr>
      <th>Nw</th>
      <th>Atleet</th>
      <th>m/v</th>
      <th>Prestative</th>
    </tr>
    </thead>
    <tbody>
    <tr>
      <td></td>
      <td>Kees</td>
      <td>m</td>
      <td>274</td>
    </tr>
    <tr style="background-color:#e6ffee;">
      <td>*</td>
      <td>Sandra</td>
      <td>v</td>
      <td>24</td>
    </tr>
    </tbody>
    </table>

The background color is never shown. And I expect it would be incorrect after sorting anyway.

2

Answers


  1. Chosen as BEST ANSWER

    I found the following to work. I had to add a tablesorter-initialized function for the formatting before any sorting is done and the sortStart function is not necessary, because apparently the td formatting is already cleared by tablesorter.

        jQuery( document ).ready( function( $ )
        {
        $("#tablesorter_Table").on( "tablesorter-initialized", function(e, table) {
          $("#tablesorter_Table td").each(function(i, e)
            { if($(e).text() == "v")  $(e).parent().children().each(function(i, e) { $(e).css("background-color", "#e6ffee"); }); } );
          } );
        $("#tablesorter_Table").on( "sortEnd", function(e, table) {
          $("#tablesorter_Table td").each(function(i, e)
            { if($(e).text() == "v")  $(e).parent().children().each(function(i, e) { $(e).css("background-color", "#e6ffee"); }); } );
          } );
        );
    

    It seems the procedure can be made more efficient because I know the column number to be checked for "v".


  2. You could try using the build in tablesorter events that can be found in the docs. Here I bound a sortStart and sortEnd event. Before recoloring, it resets the color of all rows. Once the table is sorted, it loops through all data. If one of the rows equals "v", it colors the row black.

    $("#tablesorter_Table").tablesorter();
    $("#tablesorter_Table")
            .on("sortStart",function(e, table) {
              console.log("Header clicked");
              $("#tablesorter_Table tr").each(function(i, e) {
                  $(e).css("background-color", "#ffffff");
              });
            })
            .on("sortEnd",function(e, table) {
              $("#tablesorter_Table td").each(function(i, e) {
                   if($(e).text() == "v")
                      $(e).parent().css("background-color", "#000000");
              });
            });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search