Sort columns by inserted values and checked checkboxes?

Sort columns by inserted values and checked checkboxes?

krychaj5krychaj5 Posts: 19Questions: 8Answers: 0

Hi! There is my example:
http://live.datatables.net/xupenosa/1/edit?html,css,js,output

Problem is:
There is an script, which is counting checked checkboxes per row and incrementing/decrementing value into "Rate" column. Numbers in this columns wont sort, I dont know why..

Also I want to sort columns by checked checkboxes, for example: I've checked 2 checkboxes in first column (upper and lower row), When I click thead, I want to get these rows with checked ones on top.

Is there any way to fix these things?

Answers

  • gyrocodegyrocode Posts: 126Questions: 6Answers: 30
    edited July 2017

    You need to let DataTables know that you have updated the data with row().invalidate() or similar invalidate() methods to fix sorting for the last column.

    To enable sorting by state of checkboxes, use search plug-in code from Live DOM ordering.

    For example:

    /* Create an array with the values of all the checkboxes in a column */
    $.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';
        } );
    }
    
    $(document).ready( function () {
      var table = $('#example').DataTable({
        columnDefs: [
          {
            targets: [0, 1, 2],
            orderDataType: 'dom-checkbox'
          }
        ]   
      });
      
      $(':checkbox').on('change', function(e) {
        var row = $(this).closest('tr');
        var hmc = row.find(':checkbox:checked').length;
        var kluj = parseInt(hmc);
        row.find('td.counter').text(kluj);
        table.row(row).invalidate('dom');
      });    
    });
    

    See updated example for code and demonstration.


    See more articles about jQuery DataTables on gyrocode.com.

  • LimpEmuLimpEmu Posts: 65Questions: 18Answers: 1

    Thank you for discussing this example. My datatables table now sorts correctly, however, I do not understand lines 19 through 26 shown above. In order to better understand how it works, I tried to add console.log notes, but these are never shown. How can I get console.log to show up in my console log?

    I need to add another step to the function in that I want to change the content of another column based on whether the checkbox is checked.

  • allanallan Posts: 63,468Questions: 1Answers: 10,466 Site admin

    Perhaps your console logging has been disabled or filtered out in your browser? Certainly DataTables doesn't do anything that would stop a console.log() message showing up.

    The change that is added above basically just calls row().invalidate() to make sure that DataTables is up to date with the latest data.

    Allan

This discussion has been closed.