jquery 数据tables 选定行的数据在页面导航时在分页 table 上重置

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

我正在使用 jquery 数据表。 http://jsfiddle.net/s3j5pbj4/2/ 我在分页 table.Problem 中填充了大约 3000 条记录,如果我在第一页中选择几个复选框和下拉选项并移至下一页(通过单击分页下一页按钮)并再次返回第一页,则所选数据是再次重置(即假设每个分页页面在每一页上显示 10 行,如果我在第一页上选择了 5 行然后导航到下一页并再次返回到第一页所选行的数据再次重置)。我希望我的用户应该能够看到他在任何页面上所做的所有选择,然后提交。

    $(document).ready(function() {
            var oTable = $('#dbResultsTable').dataTable({
                "sPaginationType": "full_numbers" ,
                "paging":   true,
                "ordering" : true,
                "scrollY":false,
                "autoWidth": false,
                "serverSide": false,
                 "processing": false,
                  "bDeferRender": true,
                "info":     true ,
                "lengthMenu": [[10,25,50 ,100, -1], [10,25,50, 100, "All"]],
                "scrollX": "100%" ,
                 "aoColumns":[

            { "mDataProp": null},

            { "mDataProp": "operation"}
      ],

        "sAjaxSource" : "ResultPopulator",
        "bJQueryUI" : true,
        fnRowCallback : function(nRow,aaData, iDisplayIndex) {

        jQuery('td:eq(0)', nRow).html('<input id="checkId_' + nRow+ 'name="" type="checkbox")>');
        var operationString = '<select name="operation" >';

        operationString = operationString + '<option selected disabled hidden value=""></option>';
for ( var i = 0; i < aaData.operation.length; i++) {
operationString = operationString+ '<option>'   + aaData.operation[i]+ '</option>';
}

    operationString = operationString   + '</select>';
jQuery('td:eq(1)', nRow).html(operationString);
return nRow;
},
}
);

});

function validateFields(){
    var status = true;
     var rowSelected = false ;
      var rows = $("#dbResultsTable").dataTable().fnGetNodes();
        for (var i = 0; i < rows.length; i++) {
            var cells = rows[i].cells;
            if(cells[0].children[0].checked){
                 rowSelected = true;
                 var operation =  cells[1].children[0].value;
                 if(operation==""){
                    var msz = " Please select an operation"  
                    status = false ;
                    printMsz(msz);
                     break;
                 }
            }
}

有人可以帮我解决这个问题吗?

我帮你解决了这个问题。 我向您推荐,制作 2 个 html 文件和 1 个 javascript 文件并插入我的代码(如下所示)并尝试一下。检查您的浏览器控制台,因为我添加了一些 console.log 以便您可以详细查看正在发生的事情。

此外,这是关于该主题的好读物:http://www.w3schools.com/html/html5_webstorage.asp

在我的示例中,您有 2 个 html 页面,每个页面有 3 个复选框。每次在复选框之间切换时,页面都会重新加载(并且所有内存都会丢失)。出于这个原因,我添加了一个小 JavaScript 文件,它将您选中的复选框保存在用户浏览器的 localStorage(一个 javascript 对象)中。

如果您仍然遇到问题,请告诉我。

HTML 第 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 第 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 来自嵌入文件 "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);
    }
});

请看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());
});

我稍微更新了您的代码,因为它混合了新旧选项。但是,我没有使用 aaData 属性 编辑旧版服务器响应,因此您不必更改服务器端脚本。

基本上,解决方案是使用变量(在我的示例中为 g_data)来 store/retrieve 动态表单控件的状态。

表单提交后,数据作为 JSON 字符串存储在隐藏的 INPUT 元素中。

可选地,如果需要表单验证,检查存储在 g_data 变量中的控件状态。