2

I am using jquery datatables . http://jsfiddle.net/s3j5pbj4/2/ I am populating around 3000 records in paginated table.Problem is that If am selecting few checkbox and dropdown options in first page and move to next page (by clicking on paginated next button) and again come back on first page , selected data is getting reset again (i.e. lets say every paginated page shows 10 rows on each page and if I have selected 5 rows on first page and then navigate to next page and again come back to first page selected row's data getting reset again). I want my user should be able to see what all selection he made on any page and then submit .

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

Can somebody help me on this ?

6
  • Can you create a jsfiddle? Commented Mar 15, 2015 at 6:48
  • @DelightedD0D : thanks for your quick response, i am working on jsfiddle will post jsfiddle link soon :) Commented Mar 15, 2015 at 6:56
  • @DelightedD0D : Here is the jsfiddle.net/s3j5pbj4/2 link, just select any checkbox in first page , move to next page and come back to first page, selected row will be reset , no idea why Commented Mar 15, 2015 at 9:22
  • I guess "fnDrawCallback": function() can be useful here but not sure how , Commented Mar 15, 2015 at 10:15
  • Glad Gyrocode's solution worked for you. Additionally, If you're willing to build the table yourself then apply dataTable() the table will retain all selected input without any need to specially code for each element type, see jsfiddle.net/DelightedDoD/s3j5pbj4/6 Commented Mar 15, 2015 at 18:31

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a Million , you are a genius . Thanks for all your effort. Now with your permission i will use this code and extend it according to my requirement :) .
Thank you, glad that it worked for you. Although I'm not 100% sure whether it's the optimal solution.
today i figured out one more interesting thing, if you just replace fnRowCallback : function() with "createRow":function() (which you had used in your solution), there is no need to keep track of selected row's data :) . I was using fnRowCallBack function so it was re-drawing the table everytime on navigation but "createRow":function() gets called only once for every page navigation. We got so involved in issue didn't think solution would be so simple :) . But i really appreciate efforts and solution you have given :).
1

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);
    }
});

6 Comments

This does not suit the OP's needs
@stylesenberg thanks for trying out but i guess you didn't get my question. In my case everytime if i click on next button table get re-draw and complete selected data of previous page get reset . If were to use localstorage 1) how efficient it will be , how much i can store here . I am pretty sure i am missing something here , surely datatables have this feature but not sure how to do that
@DelightedD0D : did you get a chance to look at my problem, i am struggling to find out what's wrong with my code :(
@hpppy18 localStorage may be very helpful in that matter. Not only can you save the users selections (in dropdowns & checkboxes) in the browsers localStorage, you can also refresh the data in the browser with this information (from localStorage). I really recomend you to try my answer's example and read about localStorage. IF however this may not help you, please provide me with more detailed information of what your problem is and how I can help you more. best regards.
localStorage capacity is about 5MB so you could really use that for your form (with dropdowns and checkboxes). br
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.