Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How can I sort the second column that contain 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 that image it sorting as 1,10,11,12..If I remove that image tag it sorting properly.So kindly give some solution.

$("#tb").dataTable({
    "order": [
        [1, "asc"]
    ]
});
like image 808
Pravin Avatar asked Nov 23 '15 06:11

Pravin


People also ask

How do you arrange data in ascending order in DataTable?

Using the order initialisation parameter, you can set the table to display the data in exactly the order that you want. The order parameter is an array of arrays where the first value of the inner array is the column to order on, and the second is 'asc' (ascending ordering) or 'desc' (descending ordering) as required.

How do I sort a table by number?

Sort data in a columnTap the table, then tap the letter above the column with the data you want to sort by. at the bottom of the screen, then tap an option: Sort Ascending: Sorts the table rows in alphabetical order (A to Z) or by increasing numerical values based on the data in the selected column.

Which activity should be used to sort a DataTable directly?

Core. Activities. SortDataTable Sorts an entire DataTable by ascending or descending order, based on the values of a specified column.


1 Answers

Because of the image tag, it is sorting as a string. It will start sorting with the first text it sees though, so the way i get around this is by appending a hidden span with the numerical value. You just have to remember to make all the values of same length since they will still be sorted as strings. You can do this by appending 0's.

An example [assuming i know that my number will never be over 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>

An ascending sort, even as a string, will result in 1, 24, 33, 51

like image 125
scottysmalls Avatar answered Oct 20 '22 21:10

scottysmalls