2

I need to sort a column in jQuery DataTables. I tried using the moment plugin without success.

The column contains call duration but it's not always there so we use N/A for those. Column data looks like:

2m 45s
1m 32s
N/A
45s
1m

I need to be able to sort these with the N/A valuing less than 0 and the rest to be in the logical order

I use jQuery DataTables 1.10.6, moment 2.9.0 and I do have all the datatables plugins. I use data-stype is th in the header of my table. I also use the no config datatable init looks like that

// Create DataTables User
    table = $('#summary-table').DataTable({
        'language'  : { "url": paths.lang_{{LaravelLocalization::getCurrentLocale()}} },
        'responsive':
        {
            'details':
            {
                'type': 'inline'
            }
        },
        'order': [[(nbCat + 5), 'desc']],
        'dom': '<"row"<"col-sm-12 before-table
               "<"table_controls">>r><"row"<"col-sm-12"t>><"row"<"col-sm-12"ipl>>',
        'lengthMenu': [[20, 50, 100, -1], [20, 50, 100, transAll]],
    });
3
  • JQueryUI has just the thing you want: jqueryui.com/sortable Commented Jun 19, 2015 at 20:27
  • Not quite what im looking for, it need to reoder a whole table by clicking the header. From what i see in the link its mouse sorted Commented Jun 19, 2015 at 20:30
  • I have used it in a web-app that I am working on and upon clicking on table-headers sorts entire table columns, all done with about 2 lines of code. Commented Jun 19, 2015 at 20:33

1 Answer 1

1

SOLUTION

Use the code below:

jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "duration-pre": function (s) {        
        var duration;
        
        s = s.toLowerCase();
        
        if(s === 'n/a'){ 
            duration = -1;
            
        } else {            
            d = s.match(/(?:(\d+)m)?\s*(?:(\d+)s)?/);
            duration = parseInt(d[1] ? d[1] : 0) * 60 + parseInt(d[2] ? d[2] : 0);
        }
        
        return duration;
    }
});

$(document).ready(function (){
    var table = $('#summary-table').DataTable({
       columnDefs: [
           { targets: 0, type: 'duration' }
       ]         
    });
});

Change 0 in targets: 0 to index of the column containing the duration. I omitted other table options for the sake of simplicity.

DEMO

See this jsFiddle for code and demonstration.

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

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.