Preserving checkbox state in Jquery datatable with pagination

Author - Pawandeep Kaur
22.03.2018
|
0 Comments
|

Problem:Let us assume you have many records in Jquery data table with multiple pages. You have rows with checkboxes. Now, If you want to select checkboxes from different pages of the data table and submit the page it will only provide us selected checkboxes of the currently displayed page only because data table doesn’t preserve checkbox selections across its pages.>

Solution: To solve this problem you need to maintain the state of checked checkboxes with custom Jquery. You can declare an array to which you will append selected row ids when the user checks a checkbox.

1. Initialize an array with any name like “selectedCheckBoxArray”.

2. Initially when the page loads you may auto check few checkboxes based on the state of the row in the database. In the following example, suppose you have four columns in database i.e. id, is_visible, name and email and three columns in data table i.e one for checkbox, second for the name and third for email. When you initialize the data table you can set the checked property of checkbox if that row has 1 value of “is_visible” column in database and also put id of checked checkbox into “selectedCheckBoxArray” array (that means these checkboxes should be pre-checked on data table load based on database flag and we note down their ids in our array).

Sample code:

<table id="userTable" class="large-icon-image table table-striped with-image">
             <thead>
               <tr>
                <th></th>
              <th>Name</th>
             <th>Email</th> </tr>
            </thead>
          <tbody>
       </tbody>
     </table>
  <script>

  $(document).ready(function() {
            $('#usersTable').DataTable({
                processing: true,
                serverSide: true,
         ajax: {
             url: url,
             async: false,
             type: 'POST',
             },
        columns: [{
          "data": "id",
          "data": “is_visible”,
         render: function(data, type, row) {
             if (row.is_visible == 1) {
                   var link = ‘ < input type = "checkbox"
             id = '+row.id+'
         value = '+row.id+'
    checked > ’

  rowIndex = $.inArray(row.id, selectedCheckBoxArray);
           if (rowIndex === -1) {
                selectedCheckBoxArray.push(row.id);
             } else {

     var link = ‘ < input type = "checkbox"
        id = '+row.id+'
           value = '+row.id+'
          ">’ ';
         }
        return link;
         },
           "data": "name",
           "data": "email"

         }
       ]
     });
   });

3. After loading the data table when you click on any checkbox you have to put that selected checkbox’s id into “selectedCheckBoxArray” array or remove it from the array if unchecked:

$('#usersTable tbody').on('click', 'input[type="checkbox"]', function(e) {
var checkBoxId = $(this).val();
var rowIndex = $.inArray(checkBoxId, selectedCheckBoxArray); //Checking if the
Element is in the array.
if(this.checked && rowIndex === -1) {
selectedCheckBoxArray.push(checkBoxId); // If checkbox selected and element is not in the list->Then push it in array.
}
else if (!this.checked && rowIndex !== -1) {
selectedCheckBoxArray.splice(rowrowIndex, 1); // Remove it from the array.
}
});

4. But still when you navigate different pages of data table the checked checkboxes will remain in their original state (as loaded the first time) – means UI is not reflecting what was checked or unchecked by a user – so UI is not in sync with our array. To solve this problem you can write code in the draw.dt event’s callback method. This event is fired whenever the table is redrawn on the page:

$("#usersTable").on('draw.dt', function() {
for (var i = 0; i < selectedCheckBoxArray.length; i++) {
checkboxId = selectedCheckBoxArray[i];
$('#' + checkboxId).attr('checked', true);
}
});

5. Finally, you can submit “selectedCheckBoxArray” array either using ajax or standard form submit to store newly selected checkbox values into the database.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

Send your message