Can I persist the state of check boxes?

Can I persist the state of check boxes?

StanRStanR Posts: 63Questions: 11Answers: 1

I have a check box in each row of my table (which serves as a checklist). And I need to be able to persist the value of each check box. I've tried stateSave, but that doesn't appear to work for check boxes.

My data is in a local JSON file (an array of objects). Is there an easy way to save this state?

This question has an accepted answers - jump to answer

Answers

  • gyrocodegyrocode Posts: 126Questions: 6Answers: 30

    Consider using jQuery DataTables Checkboxes which supports state saving/loading using stateSave option.


    See more articles about jQuery DataTables on gyrocode.com.

  • StanRStanR Posts: 63Questions: 11Answers: 1

    Thanks. I tried this, and it didn't work. (I'm sure I'm doing something wrong.) If I selected one check box, when I refreshed the page, ALL check boxes were checked. I aslo got the following warning: DataTables warning: table id=example - Requested unknown parameter '1' for row 0, column 1. For more information about this error, please see http://datatables.net/tn/4.

  • allanallan Posts: 63,201Questions: 1Answers: 10,415 Site admin

    We'd need a link to a page showing the issue to be able to offer any debugging help.

    Allan

  • StanRStanR Posts: 63Questions: 11Answers: 1
    edited December 2017

    I can't give you a link to a page, but here is some further information.

    The current problem is this: Each row in my table contains a check box, and there is also a select-all check box. When I check the check box in any row, the select-all check box is checked automatically. When I refresh the page, the check box on each row is selected. I would like the state of the check boxes to be same after a refresh as they were before the refresh.

    My data is in a local JSON file. It contains an array of objects.

    Here's my JavaScript:

    $(document).ready(function (){
       var table = $('#example').DataTable({
          'stateSave': true,
          'ajax': '../ajax/data/demoObjects.txt',
          'columns': [
             {
                'className':      'details-control',
                'orderable':      false,
                'data':           null,
                'defaultContent': ''
             },
             {
                 'targets': 0,
                 'checkboxes': {
                    'selectRow': true
                 },
                 'data':           null,
                 'defaultContent': ""
             },
             { 'data': 'category' },
             { 'data': 'test' },
             { 'data': 'automatable' },
             { 'data': 'priority' }
          ],
          'select': {
             'style': 'multi',
             'selector': 'td:not(:first-child)'
          },
          'order': [[1, 'asc']]
       } );
    
       // Handle form submission event
       $('#frm-example').on('submit', function(e){
          var form = this;
    
          var rows_selected = table.column(1).checkboxes.selected();
    
          // Iterate over all selected checkboxes
          $.each(rows_selected, function(index, rowId){
             // Create a hidden element
             $(form).append(
                 $('<input>')
                    .attr('type', 'hidden')
                    .attr('name', 'id[]')
                    .val(rowId)
             );
          });
       });
    
       // Add event listener for opening and closing details
       $('#example tbody').on('click', 'td.details-control', function () {
          var tr = $(this).closest('tr');
          var row = table.row( tr );
    
          if ( row.child.isShown() ) {
             // This row is already open - close it
             row.child.hide();
             tr.removeClass('shown');
          }
          else {
             // Open this row
             row.child( format(row.data()) ).show();
             tr.addClass('shown');
          }
       } );
    } );
    

    Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

  • allanallan Posts: 63,201Questions: 1Answers: 10,415 Site admin

    You would need to add the checkbox checked state into the state saving object, and then read it back and set it as required when the table is reloaded. The stateSaveParams and stateLoadParams callbacks are how that can be done.

    Allan

  • gyrocodegyrocode Posts: 126Questions: 6Answers: 30
    Answer ✓

    @allan, jQuery DataTables Checkboxes already supports state saving/loading.

    @StanR, see Child rows example on how child rows can be used with checkboxes.

    You cannot use data: null with my plug-in, that will lead to unexpected behavior. Column containing checkboxes, must contain unique data, see Known limitations.


    See more articles about jQuery DataTables on gyrocode.com.

  • allanallan Posts: 63,201Questions: 1Answers: 10,415 Site admin

    Oops - thanks for the correction. I should have guessed that it would really :).

  • StanRStanR Posts: 63Questions: 11Answers: 1

    OK, changing 'data': null to 'data': 'DT_RowId' seems to have fixed my problem. Thanks!

    Sorry for the delayed response. Had to work on something else for a bit.

  • StanRStanR Posts: 63Questions: 11Answers: 1

    I thought my problem -- saving the state of check boxes -- was fixed. However, my users are reporting errors: Sometimes, the state of the check boxes is saved, and other times it's lost. Here's a simple test case.

    1. Check some check boxes.
    2. Refresh your browser. The state of the check boxes is preserved.
    3. Refresh your browser again. The state is lost.

    Any thoughts?

  • StanRStanR Posts: 63Questions: 11Answers: 1

    I never have been able to save the state of check boxes. All other state seems to be being saved fine

    gyrocode, I have tried to follow your instructions, but am apparently doing something wrong. Can you point me to any doc or examples that might help?

  • gyrocodegyrocode Posts: 126Questions: 6Answers: 30
  • WebkungenWebkungen Posts: 2Questions: 0Answers: 0

    Hi!

    Can't get the stateSave for checkboxes working. @gyrocode I'm using your plugin (which is amazing btw!) and this is my code:

    var Tbl = $('#Tbl').DataTable( {
        ajax: {
            // ...
        },
        order: [[ 3, "asc" ], [ 6, "desc" ]],
        columnDefs: [
            {
                targets: 0,
                orderable: false,
                data: "Id",
                checkboxes: {
                    selectRow: true,
                    selectAllPages: false,
                    stateSave: false
                },
                width: 20,
            }, 
            // ... and the rest...
        ],
        stateSave: true,
        select: {
            style: 'multi'
        }
    });
    

    Only if I click F5 to refresh the state will persist but NOT the checkboxes. if I leave the page and simply press the back button in the browser whole state is restored including the checked boxes.

    Trying to achieve that search, filters etc. should we restored but the checkboxes can never be.

    Any advise? Thanks!

  • gyrocodegyrocode Posts: 126Questions: 6Answers: 30

    @Webkungen, thanks for the praise!

    Not sure what you're trying to achieve.

    If you want to enable state saving but disable checkbox state saving, your code is correct. Please make sure you're using Checkboxes v.1.2.10 where this feature become first available.

    If you want to enable state saving including checkbox state saving, remove checkboxes.stateSave option.

    See State saving example for demonstration.


    See more articles about jQuery DataTables on gyrocode.com.

  • WebkungenWebkungen Posts: 2Questions: 0Answers: 0

    Found a way around!

    stateSave: true,
    stateLoadParams: function (settings, data) {
        data.checkboxes = {};
    },
    

    Not super pretty but it does the job.

  • gyrocodegyrocode Posts: 126Questions: 6Answers: 30

    @Webkungen that may work too but I would recommend using checkboxes.stateSave option which works correctly in the example I mentioned earlier.

  • nickpapoutsisnickpapoutsis Posts: 10Questions: 2Answers: 0

    Since I have had problems with checkboxes saving their state despite using 'stateSave': false I opted for

            "stateLoadParams": function (settings, data) {
                delete data.checkboxes;
            },
    

    Note that if you use stateSaveParams instead of stateLoadParams you will end with a weird situation where checkboxes load their state the first time but if you refresh they go away.
    Maybe I'm missing something here but the above seems to be working.

This discussion has been closed.