Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort table with images jquery tablesorter

I'm trying to sort a table column whether it contains img or not. So my table html looks something like this :

<table>
<thead>
<th>One</th><th>Two</th><th>Three</th>
</thead>
<tbody>
<tr>
<td><span class="raw"><img src="path/to/image.png" /></span></td>
<td><span class="raw">text 1</span></td>
<td><span class="raw">text 2</span></td>
</tr>
<tr>
<td><span class="raw"></span></td>
<td><span class="raw">text 4</span></td>
<td><span class="raw">text 5</span></td>
</tr>
<tr>
<td><span class="raw"><img src="path/to/image.png" /></span></td>
<td><span class="raw">text 22</span></td>
<td><span class="raw">text 111</span></td>
</tr>
</tbody>
</table>

How would I sort table structure like this? With end result of sort being, the columns with image on the top or on the bottom and vice-versa

I'm using this plugin :

http://tablesorter.com/docs/

like image 465
Gandalf StormCrow Avatar asked Jan 10 '13 16:01

Gandalf StormCrow


2 Answers

Tablesorter is a great plugin - you can sort the images by the "alt" text, by defining your own text extraction function like this:

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

Cells that do not contain images will be sorted by the text.

(*) Credit to the jQuery forum for this answer

like image 169
Nimo Avatar answered Nov 15 '22 08:11

Nimo


The easiest thing to do would be to add hidden content to the image cells (demo):

$(function () {
  $('table img').each(function () {
    $(this).after('<span style="display:none">1</span>');
  });

  $('table').tablesorter();
});

Also, since it looks like you're doing alphanumeric sorting, you might want to try out my fork of tablesorter. It will correctly sort "text 22" after "text 4".

like image 29
Mottie Avatar answered Nov 15 '22 09:11

Mottie