Shruti Mundra
Shruti Mundra

Reputation: 31

DataTables - Checkbox Selection - pagination does not retain the values of the selected checkboxes

I'm using jQuery datatables on a table which contains two fields: a. image names b. image size

The first column of the table (image names) contain checkboxes for selection which I have added using html. The data in the table is updated from a textfile.

There is a button called make image set. The user should be able to select multiple images and click on the make image set button, which will show a modal with the selected image names. The user can then enter a set name and submit.

However, the problem now is that when datatables pagination takes place, the string which gets the image names (that is displayed on the modal box) only contains the image name of the current page. For example, if I select 2 images from the first page and 2 from the second and if I'm on the second page when I press the "Make image set" button, only the last two image names are displayed in the modal box.

Is there a way in which I can retain the selection of the checkboxes in order to ensure correct selection display on the modal?

The Javascript Code:

        var cellsSelected="";
$(document).ready(function() {
var dataTable = $('#table_id').DataTable( {
    columnDefs: [ {
        orderable: false,
        className: 'select-checkbox',
        targets:   0
    } ],
    select: {
        style:    'multi',
        selector: 'td:first-child'
    },
    lengthMenu: [[5,10, 25, -1], [5, 10, 25, "All"]],
    pageLength: 5 
} );
          $('checkboxed').on('click', function() {
    cellsSelected = dataTable.rows({ selected: true }).data();
});

            $('#settable_id').dataTable({
    "lengthMenu": [[5,10, 25, -1], [5, 10, 25, "All"]],
        "pageLength": 5
});
} );

The HTML Code:

<table id="table_id" class="table table-responsive table-bordered table-condensed">
   <thead>
      <tr>
         <th colspan= "2" class="text-center"><span style="color:white;" aria-hidden="true"><font size="3"><strong>Image & SMU Repository </strong></font></span>
</th>
      </tr>
      <tr>
         <td class="text-center verticalalign" style="vertical-align: middle; background-color: #98b6d9;"><span style="color: black;" aria-hidden="true"><strong>Image Name</strong></span></td>
         <td class="text-center verticalalign" style="vertical-align: middle; background-color: #98b6d9;"><span style="color: black;" aria-hidden="true"><strong>File Size</strong></span></td>
      </tr>
   </thead>
   <tbody>
      <form role="form" id="myForm" method="post">
         <div class="form-group">
            <?php $first1 = ""; $second1 = "";$str = 'size';$a=0;$mylines = file('./view_images.txt');foreach($mylines as $myline){$first1 = $second1;$second1 = $myline;$str1 = (string)$second1;if($a == 1){$sizeChunks = explode(",", $second1); ?>
            <td style="vertical-align: middle;"><span style="color:black;"><a href="./Repository.php" title="MD5 = <?php echo $sizeChunks[1] ?> " class="myClass"><?php echo preg_replace('~\D~', '', $sizeChunks[0]); ?></a></span></td>
            <?php $a=0;continue;}if($first1 == "" or $first1 == "\n"){?>
            <tr>
               <td style="vertical-align: middle;" >
                  <div class="checkbox"><label><input type="checkbox" id="checkboxed" name="myCheck" value="<?php echo $second1; ?>"><span style="color:black;"><?php echo trim($second1); ?></span></label></div>
               </td>
               <?php }else{if($second1 == "\n"){?> 
            </tr>
               <?php } else{if(strcmp(trim($str1), trim($str)) == 0){ $a=1;continue;}?>
            <td style="vertical-align: middle;"><span style="color:black;"><?php echo trim($second1); ?></span></td>
            <?php }}}?>
         </div>
      </form>
   </tbody>
</table>
<div class="modal fade" id="myModal" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title"><span style="color:black;" aria-hidden="true"></span>Create Image Sets</h4>
                    </div>
                    <div class="modal-body" id="imgmodal">
                    </div>
                    <div class="modal-footer">

                    <button type="submit" class="btn btn-primary" id="submitimgset"><span style="color:black;" aria-hidden="true"></span>Submit</button>
                    <button type="button" class="btn btn-primary" data-dismiss="modal"><span style="color:black;" aria-hidden="true></span>Cancel</button>
</div>
                </div>
            </div>
        </div>

The make image set button -

<button type="button" class="btn btn-primary btn-md" data-target="#myModal" id="make_image_set_id" onclick="imagesumrep()"><span style="color:black;" aria-hidden="true"></span>Make Image Set</button>

The Javascript function for the button -

function imagesumrep() {
            if(cellsSelected == ""){
                document.getElementById('imgmodal').innerHTML= "Error! <br> Please select images and try again!";

                                  $('#myModal').modal('show'); 

            }
            else{   
            document.getElementById('imgmodal').innerHTML= "<h4><strong><u>Images Selected:</u></strong></h4>" + "<strong>" + cellsSelected + "</strong> "+ "<br /><br />"+ "<h4><strong><u>Image Set Name:</u></strong></h4>" + "<input type ='text' name='setName' id='noname' size='70'><br /><br />";
            setTimeout(function(){
                                  $('#myModal').modal('show'); 
                              }, 600); 
           }
           }

Please help me! I'm totally new to DataTables! I've made changes as suggested by Adam. Now, the modal box is not opening at all and I'm getting an error - "Uncaught ReferenceError: dataTable is not defined".

The scripts I've included are:

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.2.0/js/dataTables.select.min.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/plug-ins/1.10.12/sorting/num-html.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap-theme.css" />
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.2.0/css/select.dataTables.min.css" />

<script src="bootstrap/js/bootstrap.min.js"></script>

Upvotes: 3

Views: 11236

Answers (1)

Adam
Adam

Reputation: 2676

Datatables is not aware of HTML changes that are made within its cells, but rather is only aware if you update it using the cell().data() method. The unshown items during pagination are not displayed in the DOM, so finding them through conventional means won't work. You'll have to collect the data via dataTables API.

Fortunately, it looks like they've built in basically what you need with the checkbox example in their documentation. Note that this uses the select extension, and you'll want the multiselect option. But, assuming you have select downloaded and included, your initialization would end up looking something like this:

$(document).ready(function() {
    var dataTable = $('#table_id').DataTable( {
        columnDefs: [ {
            orderable: false,
            className: 'select-checkbox',
            targets:   0
        } ],
        select: {
            style:    'multi',
            selector: 'td:first-child'
        },
        lengthMenu: [[5,10, 25, -1], [5, 10, 25, "All"]],
        pageLength: 5 
    } );
} );

When you want to get your selected items (this is pulled from a dataTables example as well):

var dataSelected = dataTable.rows({ selected: true }).data();

This will return an array of data from the dataTable for each row selected, which you can use in your imagesumrep() function.

I made a jsfiddle to try this out if you want to use it as a base

Upvotes: 2

Related Questions