9

I've been trying to sort a checkbox field in DataTables jQuery plugin to check and uncheck.

I'm creating the input (checkbox) inside the table like this:

'<input type="checkbox" '+ check +' />'

check is containing the text "checked" or "".

So far I tried just to add DOM checkbox type of sort, like this:

{ "sSortDataType": "dom-checkbox" }

When I use the entire code from the plugin's API documentation, I get the following error:

Uncaught TypeError: Cannot read property 'afnSortData' of undefined inside my console.


Problem: pressing on the column header won't sort the column by checked or unchecked checkboxes.

I would like to get suggestions how to fix the above mentioned error or another way to sort using only jQuery and plugin's methods.

Thanks.


EDIT

Just tried with a fixed code - no error. But sorting is messed up: it's just replacing with each other but not sorting. For example: if I have 1 checkbox checked and 9 not, the checked checkbox is switching from the third place to the sixth and again to the third and so on.

informatik01
  • 16,038
  • 10
  • 74
  • 104
Vera Gavriel
  • 381
  • 2
  • 5
  • 14
  • see here: http://stackoverflow.com/questions/13206894/column-sorting-in-jquery-datatables – MaxOvrdrv Apr 04 '13 at 23:47
  • no reference to checkbox sorting there. – Vera Gavriel Apr 04 '13 at 23:59
  • it shows you how to sort on any type of input... you just need to reference the right properties, like the (input).checked property. – MaxOvrdrv Apr 05 '13 at 00:10
  • like "sSortDataType": "dom-(input).checked" ? cause it is not working for me – Vera Gavriel Apr 05 '13 at 06:51
  • go back to the link I provided... the (input) in my comment was just an placemark... in the link I provided they permorm a sort on different input types... jusr use that example, with checkbox properties... – MaxOvrdrv Apr 05 '13 at 11:42
  • not working or i just misunderstood you. can u write the entire code function please? @MaxOvrdrv – Vera Gavriel Apr 05 '13 at 13:07
  • with little to no effort, i was able to find a direct example of what you want... on this very site we're on! Please make appropriate google searches before posting questions... http://stackoverflow.com/questions/1912957/jquery-tablesorter-sort-by-column-having-input-elements – MaxOvrdrv Apr 05 '13 at 14:43
  • ok so next time you say it just be sure about the question. im NOT using jquery tableSorter, plus i tried to use click function with jquery but wheni create a dynamic input its not recognized as input at all when i try to contact it. – Vera Gavriel Apr 05 '13 at 15:43
  • I went online, got a jQuery datatable (as stated in your question), then implemented the sort from previous link. Works perfect. in any case, I hope you find a solution. All the best! – MaxOvrdrv Apr 05 '13 at 19:57
  • https://www.datatables.net/examples/plug-ins/dom_sort.html this thing just worked. – mars-o Aug 20 '20 at 17:15

10 Answers10

11

what I did create a bool var in hidden P so it will be in the same place as the checkbox. Then I disabled the option of change value in checkbox and the sorting is now working.

SternK
  • 11,649
  • 22
  • 32
  • 46
Vera Gavriel
  • 381
  • 2
  • 5
  • 14
5

I had to slightly tweak the answer provided by Moby's Stunt Double. No additional sorting plug-in required! Just a little custom coding.

Thanks for all the ideas, everyone! For some reason I had to do special handling for my table that was not a general solution. Which was fine by me.

My checkbox was disabled and checked programatically, so I couldn't call .checked. The call based on iColumn also threw things off; probably because I had a hidden 0th column.

This is what worked for me:

$.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, iColumn ) {
    var aData = [];
    $(oSettings.oApi._fnGetTrNodes(oSettings)).each( function () {
        var checker = $(this).find('.classOnSurroundingSpan input');
        aData.push( checker.prop("checked")==true ? "1" : "0" );
    } );
    return aData;
}

My mark-up looked like this (the surrounding span was part of a solution to enable tracking a click on a disabled checkbox):

<span class='classOnSurroundingSpan'><input type='checkbox' disabled='disabled'/></span>

My table definition was (in part):

"aoColumnDefs": [
    {"sSortDataType": "dom-checkbox",
    "aTargets":[1],
    "asSorting": ["desc"]}
]
Community
  • 1
  • 1
veeTrain
  • 2,915
  • 2
  • 26
  • 43
3

Found this example:

$.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, iColumn )
{
    var aData = [];
    $( 'td:eq('+iColumn+') input', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
        aData.push( this.checked==true ? "1" : "0" );
    } );
    return aData;
}

Initialized like so:

$(document).ready(function() {
    $('#example').dataTable( {
        "aoColumns": [
            null,
            null,
            null,
            null,
            null,
            { "sSortDataType": "dom-checkbox" }
        ]
    } );
} );

Here: http://www.datatables.net/examples/plug-ins/dom_sort.html

Moby's Stunt Double
  • 2,540
  • 1
  • 16
  • 32
3

This solution worked for me so I wrote up a blog post on it.

http://blog.josephmisiti.com/sorting-booleans-in-jquery-datatables

Michael Kunst
  • 2,978
  • 25
  • 40
josephmisiti
  • 9,862
  • 11
  • 56
  • 72
3

This works for me

$(document).ready(function () {
    $('#Table').DataTable({
        "language": datatableLanguaje,
        "aoColumnDefs": [ 
            { "aTargets": [8], "orderDataType": "dom-text", type:'string' },
        ]
    });
});
Steve
  • 11,596
  • 7
  • 39
  • 53
2

this works for me:

$(document).ready(function() {
    $('#example').dataTable( {
        "aoColumns": [
            null,
            null,
            null,
            null,
            null,
            { "orderDataType": "dom-text", type: 'string' },
        ]
    } );
} );
DIG
  • 5,394
  • 2
  • 22
  • 17
2

Found this example:

  $.fn.dataTable.ext.order['dom-checkbox'] = function (settings, col) {
    return this.api().column(col, { order: 'index' }).nodes().map(function (td, i) {
        return $('input', td)[1].checked ? '1' : '0';
    });
}

Initialized like so:

$(document).ready(function() {
    $('#example').dataTable( {
        "columnDefs": [
                        {
            "targets": 10,
                            "orderDataType": "dom-checkbox"
                        });
} );
0

If you have some sort of unique identifier on the checkbox element, you can do something pretty clean like this example below (note this is a datatables sorting plugin syntax)

If your inputs look like:

<input data-app-id="1" class="migrateCheck" type="checkbox">

The plugin would look like:

function checkboxCompare(a, b) {
    var aId = $(a).data('app-id'),
        bId = $(b).data('app-id'),
        aChecked = $('.migrateCheck[data-app-id=' + aId + ']:checked').length,
        bChecked = $('.migrateCheck[data-app-id=' + bId + ']:checked').length;

    if (aChecked && !bChecked) return -1;
    else if (!aChecked && bChecked) return 1;

    return 0;
}

jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "checkbox-pre": function (a) {
        return a;
    },

    "checkbox-asc": function (a, b) {
        return checkboxCompare(a, b);
    },

    "checkbox-desc": function (a, b) {
        return checkboxCompare(b, a);
    }
});

Then simply specify sType: "checkbox" on the aoColumnDefs attr for the col that contains the checkbox.

rynop
  • 50,086
  • 26
  • 101
  • 112
0

Anything can be sorted on by some simple html.

$('#table input[type=checkbox]').each(function () {
    var text = $(this).prop('checked');
    var ele = $('<span>' + text + '</span>').hide();
    $(this).after(ele);
});
Tim
  • 85
  • 1
  • 8
0

This stumped me for a bit.

I used the standard Plugin Code https://datatables.net/plug-ins/sorting/custom-data-source/dom-checkbox:

$.fn.dataTable.ext.order['dom-checkbox'] = function  ( settings, col )
{
    return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
        return $('input', td).prop('checked') ? '1' : '0';
    } );
};

You need to specify "dom-checkbox" column types are sortable:

$('#myTable').dataTable({
    "aoColumnDefs": [
        { "bSortable": false, "aTargets": [ "action" ] },
        { "sSortDataType": "dom-checkbox", "aTargets": [ "enabled" ] }
    ],
    "aaSorting": [
        [ 3, "desc" ]
    ]
});

In the view I enable the CheckBox columns to put the checkbox in (not tied to col number):

<th class="enabled">Enabled</th>
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321