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.

10
  • see here: stackoverflow.com/questions/13206894/… Commented Apr 4, 2013 at 23:47
  • no reference to checkbox sorting there. Commented Apr 4, 2013 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. Commented Apr 5, 2013 at 0:10
  • like "sSortDataType": "dom-(input).checked" ? cause it is not working for me Commented Apr 5, 2013 at 6: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... Commented Apr 5, 2013 at 11:42

10 Answers 10

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.

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

3 Comments

i have a similar situation, my problem is that when i sort the checkbox, the control is not going to the function defined for it ,i have a function named dom-checkbox defined, and the sSortDataType is dom-checbox, can u help ?
Plz can you provide the code snippet, as i am also facing same issue
@SachinGaikwad <td><input type='checkbox' class='minimal' "+product_enabled+"><p style='visibility: hidden; display: none;'>"+products[i].enabled+"</p></td>
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"]}
]

Comments

4

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

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

Comments

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

3 Comments

i wrote that this example gets an error and i wrote what kind of error it is in m question.
Do you have a thead tag and th tags for your headers by chance? I had issues once with DataTables and a poorly marked up table.
th tags inside thead tags @Moby's Stunt Double
3

This works for me

$(document).ready(function () {
    $('#Table').DataTable({
        "language": datatableLanguaje,
        "aoColumnDefs": [ 
            { "aTargets": [8], "orderDataType": "dom-text", type:'string' },
        ]
    });
});

Comments

2

this works for me:

$(document).ready(function() {
    $('#example').dataTable( {
        "aoColumns": [
            null,
            null,
            null,
            null,
            null,
            { "orderDataType": "dom-text", type: 'string' },
        ]
    } );
} );

Comments

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"
                        });
} );

Comments

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.

Comments

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);
});

Comments

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>

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.