jquery数据表选择行的数据在页面上导航时在分页表上重置

时间:2015-03-15 06:42:08

标签: javascript jquery jquery-datatables

我正在使用jquery数据表。 http://jsfiddle.net/s3j5pbj4/2/ 我在分页表中填充了大约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 个答案:

答案 0 :(得分:4)

请查看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)来存储/检索动态表单控件的状态。

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

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

答案 1 :(得分:1)

我为你解决了这个问题。 我建议你,制作2个html文件和1个javascript文件并插入我的代码(如下),然后玩一下它。检查你的浏览器控制台,因为我添加了一些console.log,以便你可以详细了解发生了什么。

这也是关于这个主题的好读物:http://www.w3schools.com/html/html5_webstorage.asp

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

告诉我你是否还有麻烦。

第1页的HTML:

<!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>

第2页的HTML:

<!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>

来自嵌入文件“my_javascript.js”的JAVASCRIPT

$("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);
    }
});