How to post data for the whole table using jQuery DataTables

后端 未结 1 835
北荒
北荒 2020-12-01 23:08

I have a table working with jQuery DataTables and pagination

I have over 300 registrys which 50 are the max on each page. Every time I change from page to page the o

相关标签:
1条回答
  • 2020-12-01 23:40

    CAUSE

    When using DataTables plug-in with pagination only current page rows exist in the DOM for performance and compatibility. Therefore when you submit the form, only current page form controls values are being submitted.

    SOLUTION 1: Submit form directly

    The trick is to turn form elements from pages other than current into <input type="hidden"> before submitting the form.

    var table = $('#example').DataTable();
    
    // Handle form submission event
    $('#frm-example').on('submit', function(e){
       var form = this;
    
       // Encode a set of form elements from all pages as an array of names and values
       var params = table.$('input,select,textarea').serializeArray();
    
       // Iterate over all form elements
       $.each(params, function(){
          // If element doesn't exist in DOM
          if(!$.contains(document, form[this.name])){
             // Create a hidden element
             $(form).append(
                $('<input>')
                   .attr('type', 'hidden')
                   .attr('name', this.name)
                   .val(this.value)
             );
          }
       });
    });
    

    See jQuery DataTables: How to submit all pages form data - Submit directly for more details and examples.

    SOLUTION 2: Submit form via Ajax

    Another solution is to submit the form via Ajax.

    var table = $('#example').DataTable();
    
    // Handle form submission event
    $('#frm-example').on('submit', function(e){
       // Prevent actual form submission
       e.preventDefault();
    
       // Serialize form data
       var data = table.$('input,select,textarea').serialize();
    
       // Submit form data via Ajax
       $.ajax({
          url: '/echo/jsonp/',
          data: data,
          success: function(data){
             console.log('Server response', data);
          }
       });
    });
    

    See jQuery DataTables: How to submit all pages form data - Submit via Ajax for more details and examples.

    NOTES

    Please note that both solutions will work in client-side processing mode only.

    LINKS

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

    0 讨论(0)
提交回复
热议问题