How to submit checkboxes from all pages with jQuery DataTables

后端 未结 4 1002
执念已碎
执念已碎 2020-12-06 01:11

I\'m trying to get first cell (td) for each row and getting it but only for current page. If I navigate to next page then the checkbox checked on the previous p

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 02:13

    CAUSE

    jQuery DataTables removes non-visible rows from DOM for performance reasons. When form is submitted, only data for visible checkboxes is sent to the server.

    SOLUTION 1. Submit form

    You need to turn elements that are checked and don't exist in DOM into upon form submission.

    var table = $('#example').DataTable({
       // ... skipped ...
    });
    
    $('form').on('submit', function(e){
       var $form = $(this);
    
       // Iterate over all checkboxes in the table
       table.$('input[type="checkbox"]').each(function(){
          // If checkbox doesn't exist in DOM
          if(!$.contains(document, this)){
             // If checkbox is checked
             if(this.checked){
                // Create a hidden element 
                $form.append(
                   $('')
                      .attr('type', 'hidden')
                      .attr('name', this.name)
                      .val(this.value)
                );
             }
          } 
       });          
    });
    

    SOLUTION 2: Send data via Ajax

    var table = $('#example').DataTable({
       // ... skipped ...
    });
    
    $('#btn-submit').on('click', function(e){
       e.preventDefault();
    
       var data = table.$('input[type="checkbox"]').serializeArray();
    
       // Include extra data if necessary
       // data.push({'name': 'extra_param', 'value': 'extra_value'});
    
       $.ajax({
          url: '/path/to/your/script.php',
          data: data
       }).done(function(response){
          console.log('Response', response);
       });
    });
    

    DEMO

    See jQuery DataTables: How to submit all pages form data for more details and demonstration.

    NOTES

    • Each checkbox should have a value attribute assigned with unique value.
    • Avoid using id attribute check for multiple elements, this attribute is supposed to be unique.
    • You don't need to explicitly enable paging, info, etc. options for jQuery DataTables, these are enabled by default.
    • Consider using htmlspecialchars() function to properly encode HTML entities. For example, .

提交回复
热议问题