jquery datatables selected row's data getting reset on paginated table while navigating on pages

▼魔方 西西 提交于 2019-12-03 09:05:53

Please take a look at my solution at JSFiddle.

HTML

<table id="test" class="display">
    <thead><tr><th>select</th><th>operation</th></tr></thead>
    <tbody></tbody>
</table>

<p>
    <input id="test-data-json" name="test_data_json" type="hidden">
    <button id="btn-submit">Submit</button>
</p>

Javascript:

//ajax emulation
$.mockjax({
   url: '/test/0',
   responseTime: 200,
   responseText: {
      "aaData" : [
         [{"id":1}, {"chk":"on"}, {"operation":["Modify", "Delete"]}],
         [{"id":2}, {"chk":"on"}, {"operation":["Modify", "Delete"]}],
         [{"id":3}, {"chk":"on"}, {"operation":["Modify", "Delete"]}],
         [{"id":4}, {"chk":"on"}, {"operation":["Modify", "Delete"]}],
         [{"id":5}, {"chk":"on"}, {"operation":["Modify", "Delete"]}],
         [{"id":6}, {"chk":"on"}, {"operation":["Modify", "Delete"]}],
         [{"id":7}, {"chk":"on"}, {"operation":["Modify", "Delete"]}]
      ]
   }
});

// Global variable holding current state of the controls in the data table
var g_data = {};

var $table = $('#test');
$table.dataTable( {
   "lengthMenu": [[2,25,50 ,100, -1], [2,25,50, 100, "All"]],
   "pagingType": "full_numbers" ,
   "paging":   true,
   "ordering" : true,
   "scrollY":false,
   "autoWidth": false,
   "serverSide": false,
   "processing": false,
   "info":     true ,
   "deferRender": true,
   "processing": true,
   "columns": [
      ["data", 1 ],
      ["data", 2 ]
   ],
   "ajax" : {
      "url": "/test/0",
      "dataSrc" : function(json){
         var data = json.aaData;
         for (var i = 0; i < data.length; i++){
            var chk_name  = 'chk_' + data[i][0].id;

            // If checkbox was never checked
            if(typeof g_data[chk_name] === 'undefined'){
               // Retrieve checkbox state from received data
               g_data[chk_name] = (data[i][1].chk === 'on') ? true : false;
            }
         }

         return data;
      }
   },
   "createdRow" : function( row, data, index ){
      var chk_name  = 'chk_' + data[0].id;
      var chk_checked = (g_data[chk_name]) ? " checked" : "";

      $('td:eq(0)', row)
         .html('<input name="' + chk_name +'" type="checkbox" value="1"' + chk_checked + '>');

      var select_name = 'select_' + data[0].id;
      html =
         '<select name="' + select_name +'">'
          + '<option value="">Select one</option>'
          + '<option'
          + ((typeof g_data[select_name] !== 'undefined' && g_data[select_name] === data[2].operation[0]) ? ' selected' : '')
          + '>' + data[2].operation[0] + '</option>'
          + '<option'
          + ((typeof g_data[select_name] !== 'undefined' && g_data[select_name] === data[2].operation[1]) ? ' selected' : '')
          + '>' + data[2].operation[1] + '</option>';
          + '</select>';

      $('td:eq(1)', row).html(html);
   },
});

$('#test tbody').on('click', 'input[type=checkbox]', function (e){
   g_data[this.name] = this.checked;
});

$('#test tbody').on('change', 'select', function (e){
   if(this.selectedIndex != -1){
      var value = this.options[this.selectedIndex].value;
      g_data[this.name] = value;
   }
});

$('#btn-submit').on('click', function(){
   $('#test-data-json').val(JSON.stringify(g_data));
   console.log($('#test-data-json').val());
});

I have slightly updated your code since it was a mix of new and legacy options. However I haven't edited legacy server response using aaData property, so you don't have to change your server-side script.

Basically, the solution is to use a variable (g_data in my example) to store/retrieve state of dynamic form controls.

Upon form submission, the data is stored in hidden INPUT element as JSON string.

Optionally, if form validation is needed, inspect the state of controls stored in g_data variable.

I solved this for you. I recommend to you, to make 2 html files and 1 javascript file and insert my code (below) and play around a little with it. Check your Browsers console, because I added some console.log's so that you can see what is going on in detail.

Also THIS is a good read on the topic: http://www.w3schools.com/html/html5_webstorage.asp

In my example you have 2 html pages with 3 checkboxes each. Every time you switch between the checkboxes, the page gets reloaded (and all memory is lost). For this reason I added a little JavaScript file, that saves your checked checkboxes in the localStorage (a javascript object) of the users Browser.

Tell me if you still experience troubles.

HTML of PAGE 1:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Test Page</title>

  <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-1.16.0.css">

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>

    <input type="checkbox" name="item_1">
    <label>Item #1</label>
    <br>

    <input type="checkbox" name="item_2">
    <label>Item #2</label>
    <br>

    <input type="checkbox" name="item_3">
    <label>Item #3</label>
    <br>

    <nav>
      <ul class="pagination">
        <li>
          <a href="#" aria-label="Previous">
            <span aria-hidden="true">&laquo;</span>
          </a>
        </li>
        <li><a href="index.html">1</a></li>
        <li><a href="page2.html">2</a></li>
        <li>
          <a href="#" aria-label="Next">
            <span aria-hidden="true">&raquo;</span>
          </a>
        </li>
      </ul>
    </nav>

    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="my_javascript.js" type="text/javascript"></script>
</body>
</html>

HTML of PAGE 2:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Test Page</title>

  <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-1.16.0.css">

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>

    <input type="checkbox" name="item_4">
    <label>Item #4</label>
    <br>

    <input type="checkbox" name="item_5">
    <label>Item #5</label>
    <br>

    <input type="checkbox" name="item_6">
    <label>Item #6</label>
    <br>

    <nav>
      <ul class="pagination">
        <li>
          <a href="#" aria-label="Previous">
            <span aria-hidden="true">&laquo;</span>
          </a>
        </li>
        <li><a href="index.html">1</a></li>
        <li><a href="page2.html">2</a></li>
        <li>
          <a href="#" aria-label="Next">
            <span aria-hidden="true">&raquo;</span>
          </a>
        </li>
      </ul>
    </nav>

    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="my_javascript.js" type="text/javascript"></script>
</body>
</html>

JAVASCRIPT from the embedded file "my_javascript.js"

$("input").click(function(){

    var key = $("input:hover").attr("name"); 
    var value = $("input:hover").attr("name");
    var item_is_present = false;

    console.log(key);
    console.log(value);

    if ( localStorage.getItem(key) != null ){
        localStorage.removeItem(key);
    } else {
        localStorage.setItem(key, value);
    };

    console.log(localStorage);
    console.log(localStorage.length);
});

$(function(){
    for ( var i = 0, len = localStorage.length; i < len; ++i ) {

        var myVar = localStorage.getItem( localStorage.key( i ) ) ;

        $("input[name=" + myVar + "]").prop("checked", true);
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!