19

I have a table which contains columns of numbers and NA.

<tr>
    <td>NA</td>
</tr>
<tr>
    <td>1024</td>
</tr>
<tr>
    <td>100</td>
</tr>
<tr>
    <td>200</td>
</tr>
<tr>
    <td>300</td>
</tr>
<tr>
    <td>2096</td>
</tr>

I'm trying to use jQuery dataTable to sort the column to produce the following:

NA, 100, 200, 300, 1024, 2096 and 2096, 1024, 300, 200, 100, NA

but can't figure out how to do it from reading the sorting and plugins docs.

I've created a Fiddle of the code here: http://jsfiddle.net/stowball/rYtxh/ and would really appreciate some assistance.

2
  • 2
    if you use "-" instead of "NA" it works fine here is js fiddle jsfiddle.net/stowball/rYtxh Commented Jul 23, 2013 at 10:23
  • @umesh25 Thanks, that's really interesting! If I don't get any other solutions, I may have to do that. Commented Jul 23, 2013 at 10:30

2 Answers 2

38

Simply use data-order attribute in <td> element. Plugin will sort based on that. For your case the HTML will be:

<tr>
    <td data-order="-1">NA</td>
</tr>
<tr>
    <td data-order="1024">1024</td>
</tr>
<tr>
    <td data-order="100">100</td>
</tr>
<tr>
    <td data-order="200">200</td>
</tr>
<tr>
    <td data-order="300">300</td>
</tr>
<tr>
    <td data-order="2096">2096</td>
</tr>

More HTML5 attributes are available to solve problems of filtering, sorting, searching, etc.

https://datatables.net/examples/advanced_init/html5-data-attributes.html

Sign up to request clarification or add additional context in comments.

3 Comments

the answer is helpful, the position of the quotes are wrong.
Thanks @Ken for highlighting
Thanks @Aziz Saleh for the Edit
17

By looking at the Numbers with HTML plugin you can take the existing code and modify the regex to look for negative numbers instead of stripping everything. Using that you can put together a HTML tag around the "NA" and use the HTML5 data-internalid to store the lowest number of the collection.

so it becomes:

<td><a data-internalid="-1">NA</a></td>

and (notice the regex)

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"num-html-pre": function ( a ) {
    var x = String(a).replace(/(?!^-)[^0-9.]/g, "");
    return parseFloat( x );
},

"num-html-asc": function ( a, b ) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},

"num-html-desc": function ( a, b ) {
    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}});

Then in the datatable, set the type to num-html

$('table').dataTable({
    "aoColumns": [{ "sType": "num-html" }],
    "aaSorting": [[ 0, "desc" ]],
});

You can see my full solution here: http://jsfiddle.net/rYtxh/4/

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.