Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery tablesorter: custom html image tag sorter/parser

I am using the jQuery tablesorter plugin. It seems to be working fine except that it can't sort rows with image tags as their content. I want to implement something that just sorts by the src attribute of the image tag. I have tried a number of things but can't seem to get it to work.

Problems:

  • The plugin does not detect my image columns with the image parser, it detects it as using the digit parser, so I have to specify the image parser manually.
  • The s argument being passed to the format function of my parser seems to be blank/null/undefined (something like that, I can't tell).

Code:

JavaScript:

$.tablesorter.addParser({ 
    id: 'image', 
    is: function(s) {
        //i think this works
        return /^<img(.*)>$/.test(s);
    }, 
    format: function(s) { 
        //neither of these work
        return $(s).attr('src').toLowerCase();
        return s.match(/src="(.*)"/);
    },
    type: 'text' 
}); 
$(document).ready(function() { 
    $("table").tablesorter(); 
}); 

HTML:

<table>             
    <thead> 
        <tr> 
            <th>text column</th> 
            <th class="{sorter: 'image'}">image column</th>  
        </tr> 
    </thead> 
    <tbody> 
        <tr> 
            <td>a</td> 
            <td><img src="d.gif"></td> 
        </tr> 
        <tr> 
            <td>b</td> 
            <td><img src="c.gif"></td> 
        </tr> 
        <tr> 
            <td>c</td> 
            <td><img src="b.gif"></td> 
        </tr> 
        <tr> 
            <td>d</td> 
            <td><img src="a.gif"></td> 
        </tr> 
    </tbody>
</table>
like image 341
Andrew Avatar asked Apr 14 '26 21:04

Andrew


1 Answers

One way given your markup would be to scrap the custom parser and do the following.

$("table").tablesorter({
     textExtraction:function(s){
        var $el = $(s),
        $img = $el.find('img');
        return $img.length ? $img[0].src : $el.text();
     }  
});
like image 177
redsquare Avatar answered Apr 17 '26 13:04

redsquare