justjoe300
justjoe300

Reputation: 81

Why won't .datatables sort properly?

I am using the jquery plugin .dataTables and cannot get it to sort properly. After reading similar questions on stack overflow I am still confused and need help! I am posting the code below. Any help would be appreciated. Here is the portion of html for the table:

<thead>
     <tr>
        <th>Store Name</th>
        <th>District Manager</th>
        <th>Store ID</th>
        <th>Payday</th>
        <th>Title</th>
        <th>Payday/Title Total</th>
     </tr>
</thead>
<tbody>
<?php
foreach($bigQuery as $i => $row) {
    $total = $row['mtd_payday'] + $row['mtd_title'];
    echo "<tr>" . "<td>" . $row['store_name'] . "</td>";
    echo "<td >" . $row['district_manager'] . "</td>";
    echo "<td >" . $row['store_id'] . "</td>";
    echo "<td data-sort=\"". $row['mtd_payday']. "\">" . money_format('%.2n',  $row['mtd_payday']) . "</td>";
    echo "<td data-sort=\"". $row['mtd_title']. "\">" . money_format('%.2n',  $row['mtd_title']) . "</td>";
    echo "<td data-sort=\"$total\">" . money_format('%.2n',  $total) . "</td>" . "</tr>";
    $total = "";
} ?> 
</tbody>

I am populating the table with data from a query. the javascript for the table is below:

<script>
//initializes the dataTable plugin. 
$(document).ready(function() {
    var table = $('#balances').DataTable({
        tableTools: {
            "sSwfPath": "../copy_csv_xls_pdf.swf"  
        }
});
var tt = new $.fn.dataTable.TableTools( table );
$( tt.fnContainer() ).insertBefore('div.dataTables_wrapper');  }); 
</script>

I am a new programmer and totally new to the .dataTables plugin. When I try to use the sort buttons at the top of the table, it does not sort properly.

Upvotes: 1

Views: 3211

Answers (1)

Stryner
Stryner

Reputation: 7318

Datatables should sort by default. That leads me to believe that there is a problem with your html syntax.

After checking I noticed that your ending <tr> in <thead> is incorrect. Add the / and make it </tr>


After seeing your picture, it is sorting it and treating the columns as strings. In order to change the data-type of a column for sorting, you need to add sType to the columns. The default supported types are string, numeric, date and html.

The code should be changed to:

var table = $('#balances').DataTable({
    "aoColumns": [
        null,
        null,
        null,
        { "sType": "numeric" },
        { "sType": "numeric" },
        { "sType": "numeric" }
    ],
    tableTools: {
        "sSwfPath": "../copy_csv_xls_pdf.swf"  
    }
});

Upvotes: 1

Related Questions