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/
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
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With