3

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>

2 Answers 2

3

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();
     }  
});
Sign up to request clarification or add additional context in comments.

1 Comment

the fact that you are using the $el variable on the same line as you are assigning it (separated by a comma) is sort of blowing my mind right now. But it works! And it solves my immediate problem for now. Thanks!
0

The issue involves tablesorter's use of innerHTML when it should be using innerText: jquery tablesorter custom parser - innerHTML vs. innerText

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.