How can I sort a column that contains a number and an image using datatable

How to sort the second column containing the image and number.

<table id='tb' class="table table-bordered table-striped table-hover"> <tr> <td>status</td> <td><img src='edit.png'>1</td> </tr> <tr> <td>status</td> <td><img src='edit.png'>2</td> </tr> <tr> <td>status</td> <td><img src='edit.png'>3</td> </tr> </table> 

I tried like this: because of this image, it is sorted as 1,10,11,12. If I remove this image tag, it sorts correctly. So kindly give some solution.

 $("#tb").dataTable({ "order": [ [1, "asc"] ] }); 
+8
jquery sorting html
source share
3 answers

Due to the image tag, it is sorted as a string. It will start sorting with the first text that it sees, so the way I get around this is to add a hidden range with a numeric value. You just have to remember to make all the values ​​the same length, since they will still be sorted as strings. You can do this by adding 0.

Example [assuming that I know that my number will never be more than 100]:

 <td><span style="display:none">024</span><img src='edit.png'>24</td> ... <td><span style="display:none">001</span><img src='edit.png'>1</td> ... <td><span style="display:none">033</span><img src='edit.png'>33</td> ... <td><span style="display:none">051</span><img src='edit.png'>51</td> 

Upward sorting, even as a string, will result in 1, 24, 33, 51

+1
source share

Sorting is much more flexible in the current version of dataTables with the inclusion of HTML5 data attributes .

Attaching data or data sort attributes to the td tag allows you to customize the sort order for all types of dom objects in your tables.

 <table id='tb' class="table table-bordered table-striped table-hover"> <tr> <td>status</td> <td data-order='1'><img src='edit.png'>1</td> </tr> <tr> <td>status</td> <td data-order='2'><img src='edit.png'>2</td> </tr> <tr> <td>status</td> <td data-order='3'><img src='edit.png'>3</td> </tr> </table> 
+1
source share

Based on the comments of @Guruprasad Rao and the plugin docs ( http://datatables.net/plug-ins/sorting#hidden_title_string ), you should create your own filter. Something like that:

Filter Code:

 /* Create an array with the values of all the input boxes in a column */ $.fn.dataTable.ext.order['dom-inner-text'] = function ( settings, col ) { return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) { return td.text(); } ); } 

Then in the datatable init function:

 $('#example').DataTable( { "columns": [ null, { "orderDataType": "dom-inner-text" }, .... ] } ); 
0
source share

All Articles