Search code examples
javascriptjquerytablesorter

jQuery tablesorter - images


I have a with three columns and I am using jQuery tablesorter to sort these columns. The code for the table is listed below. One of the columns is a "yes/no" field but I am displaying a "thumbs-up/thumbs-down" image instead. I want to sort by the "yes/no" value while still displaying the "thumbs-up/thumbs-down" images. How can I achieve this while using tablesorter?

<script type="text/javascript">
  $(function() {
      $("#myTable").tablesorter();
  });
</script>

<table id="myTable" class="tablesorter">
        <thead>
            <tr>
                <th>Subscription Product Name</th>
                <th>Type</th>
                <th>Has Fees</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var categories in Model.Categories)
            {
                foreach (product p in categories)
                {
                    <tr>
                        <td>
                            @p.name
                        </td>
                        <td>
                            @p.type
                        </td>
                        <td>
                            @DisplayThumbsUpDown(p.hasfees)
                        </td>
                    </tr>
                }
            }
        </tbody>
    </table>
  
    @helper DisplayThumbsUpDown(HasFees fees)
    {
        switch (fees)
        {
            case HasFees.Yes:
                    <img src="/lib/images/thumbs-up.png">break;
            case HasFees.No:
                    <img src="/lib/images/thumbs-down.png">break;
            default:
                    <span>&mdash;</span>break;
        }
    }

Solution

  • Include the alt attr in the image tag like

    <img src="/lib/images/thumbs-up.png" alt="0">
    <img src="/lib/images/thumbs-down.png" alt="1">
    

    and use

    $("#myTable").tablesorter({
        textExtraction:function(s){
            if($(s).find('img').length == 0)
                return $(s).text();
            else
                return $(s).find('img').attr('alt');
        }
    });
    

    Refer : https://forum.jquery.com/topic/tablesorter-sort-image