title: Implementing checkbox selection in datatables with Json data source
body: <p>I'm trying to implement multiple row selection using checkboxes in my datatable and can't seem to get the checkbox to appear.</p>
  
  <p>I followed this article word for word <a href="http://www.gyrocode.com/articles/jquery-datatables-how-to-add-a-checkbox-column/" rel="nofollow">http://www.gyrocode.com/articles/jquery-datatables-how-to-add-a-checkbox-column/</a> and it's been helpful but i'm not sure what to do from here.</p>
  
  <p>Beforehand I was using the innerHTML of a column to hold a checkbox for each row but now that I need to be able to select multiple rows I think it's better to use something proven to work like the example in the article.</p>
  
  <p>Anyway, what I had before was this:</p>
  
  <pre><code>    $(document).ready(function () {
          var userData = @Html.Raw(Model.EditUserGroupListJson);
          var table = $('#viewUsers').DataTable({
              "data": userData,
              "columns": [
                  { "title": "Email" },
                  { "title": "Full Name" },
                  { "title": "Member" }
              ],
  
              "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                  var tblTds = $('&gt;td', nRow);
                  $(nRow).attr("id", 'tblRow_' + aData[2]);
  
                  if (aData[3] == '0')
                  {
                      tblTds[2].innerHTML = '&lt;td&gt;&lt;input type="checkbox" name="enrolstatus" value="' + aData[2] + '" id="' + aData[2] + '" onclick="Member(' + aData[2] + ')" /&gt;&lt;label for="' + aData[2] + '"&gt;&lt;/label&gt;&lt;/td&gt;';
                  }
                  else
                  {
                      tblTds[2].innerHTML = '&lt;td&gt;&lt;input type="checkbox" name="enrolstatus" value="' + aData[2] + '" id="' + aData[2] + '" checked="checked" onclick="Member(' + aData[2] + ')" /&gt;&lt;label for="' + aData[2] + '"&gt;&lt;/label&gt;&gt;&lt;/td&gt;';
                  }
              }
          })
      });
  </code></pre>
  
  <p>and now:</p>
  
  <pre><code>    $(document).ready(function () {
          var userData = @Html.Raw(Model.EditUserGroupListJson);
          var table = $('#viewUsers').DataTable({
              'data': userData,
              'columnDefs': [{
                  'targets': 0,
                  'searchable': false,
                  'orderable': false,
                  'className': 'dt-body-center',
                  'render': function (data, type, full, meta){
                      return '&lt;input type="checkbox" name="id[]" value="'+ $('&lt;div/&gt;').text(data).html() + '"&gt;';
                  }
              }],
              'order': [[1, 'asc']],
  
              'fnRowCallback': function(nRow, aData, iDisplayIndex, iDisplayIndexFull){
                  var tblTds = $('&gt;td', nRow);
                  $(nRow).attr("id", 'tblRow_' + aData[3]);
              }
          });
  
          //handle click on 'select all' control
          $('#example-select-all').on('click', function(){
              //get all rows with search applied
              var rows = table.rows({ 'search': 'applied' }).nodes();
              //check or uncheck boxes for all rows in the table
              $('input[type="checkbox"]', rows).prop('checked', this.checked);
          });
  
          //handle click on checkbox to set state of 'select all' control
          $('#example tbody').on('change', 'input[type="checkbox"]', function(){
              //if checkbox is not checked
              if(!this.checked){
                  var el = $('#example-select-all').get(0);
                  // if 'select all' control is checked and has indeterminate property
                  if (el &amp;&amp; el.checked &amp;&amp; ('indeterminate' in el)){
                      //set visual state of 'select all' control as indeterminate
                      el.indeterminate = true;
                  }
              }
          });
  
          //handle form submission event
          $('#frm-example').on('submit', function(e){
              var form = this;
  
              //iterate over all checkboxes in the table
              table.$('input[type="checkbox"]').each(function(){
                  //if checkbox doesnt exist in DOM
                  if(!$.contains(document, this)){
                      //if checkbox is checked
                      if(this.checked){
                          //create hidden element
                          $(form).append(
                              $('&lt;input&gt;')
                                  .attr('type', 'hidden')
                                  .attr('name', this.name)
                                  .val(this.value)
                              );
                      }
                  }
              });
          });
      });
  </code></pre>
  
  <p>My html:</p>
  
  <pre><code>    &lt;table id="viewUsers" class="display table table-bordered" cellspacing="0" width="100%"&gt;
          &lt;thead&gt;
              &lt;tr&gt;
                  &lt;th&gt;&lt;input name="select_all" value="1" id="example-select-all" type="checkbox"&gt;&lt;/th&gt;                  
                  &lt;th&gt;Email&lt;/th&gt;
                  &lt;th&gt;Full Name&lt;/th&gt;
                  &lt;th&gt;Member&lt;/th&gt;
              &lt;/tr&gt;
          &lt;/thead&gt;
      &lt;/table&gt;
  </code></pre>
  
  <p>Json:</p>
  
  <pre><code>select new string[] {"", user.Email, user.Forename + ' ' + user.Surname, user.UserID.ToString(), user.CategoryMaps.Where(c =&gt; c.CategoryID == id).Count().ToString() };
  
  // if ticked, AddUser, otherwise RemoveUser
  function Member(userID) {
      var fullURL = document.URL;
      var url = fullURL.split('EditUserGroup/');
      var categoryID = url[1];
      var postData = { 'userId': userID, 'categoryID': categoryID };
      if ($("#" + userID).is(':checked')) {
          $.post('/Admin/AddCategoryUser/', postData, function (data) {});
      }
      else {
          $.post('/Admin/RemoveCategoryUser/', postData, function (data) {});
      }
  };
  </code></pre>
  
  <p>I've also put a blank " " at the start of my JSON to allow for the checkbox (I think) and i'm quite stuck at the moment.</p>
  
  <p>Any help would be greatly appreciated, thank you.</p>
  
  <p><strong>Newest code</strong></p>
  
  <p>JS:</p>
  
  <p>$(document).ready(function () {
          var userData = @Html.Raw(Model.EditUserGroupListJson);</p>
  
  <pre><code>    var table = $('#viewUsers').DataTable({
          'data': userData,
          'columnDefs': [{
              'targets': 0,
              'searchable': false,
              'orderable': false,
              //'className': 'dt-body-center',
              'render': function (data, type, full, meta) {
                  return '&lt;input type="checkbox" name="id[]" value="'
                     + $('&lt;div/&gt;').text(data).html() + '"&gt;';
              }
          }],
          'order': [1, 'asc'],
          "createdRow": function (row, data, dataIndex) {
              $(row).attr("id", "tblRow_" + data[0]);
          }
      });
  
      // handle select all click control
      $('#example-select-all').on('click', function () {
          // check/uncheck all checkboxes in the table
          var rows = table.rows({ 'search': 'applied' }).nodes();
          $('input[type="checkbox"]', rows).prop('checked', this.checked);
      });
  
      // handle click on checkbox to set state of select all control
      $('#example tbody').on('change', 'input[type="checkbox"]', function () {
          // if checkbox is not checked
          if (!this.checked) {
              var el = $('#example-select-all').get(0);
              // if select all control is checked and has 'indeterminate' property
              if (el &amp;&amp; el.checked &amp;&amp; ('indeterminate' in el)) {
                  // set visual state of select all control as interminate
                  el.indeterminate = true;
              }
          }
      });
  
      $('#frm-example').on('submit', function (e) {
          var form = this;
  
          // iterate over all checkboxes in the table
          table.$('input[type="checkbox"]').each(function () {
              // if checkbox doesn't exist in DOM
              if (!$.contains(document, this)) {
                  // if checkbox is checked
                  if (this.checked) {
                      // create a hidden element
                      $(form).append(
                          $('&lt;input&gt;')
                              .attr('type', 'hidden')
                              .attr('name', this.name)
                              .val(this.value)
                      );
                  }
              }
          });
  
          //testing only
  
          // output form data to console
          $('#example-console').text($(form).serialize());
          console.log("Form submission", $(form).serialize());
  
          // prevent actual form submission
          e.preventDefault();
      });
  });
  </code></pre>
  
  <p>HTML:</p>
  
  <h3>User Group Membership</h3>
  
  <pre><code>        &lt;form id="frm-example" @*action="path/to/script"*@ method="post"&gt;
          &lt;table id="viewUsers" class="display table table-bordered" cellspacing="0" width="100%"&gt;
              &lt;thead&gt;
                  &lt;tr&gt;
                      &lt;th&gt;&lt;input name="select_all" value="1" id="example-select-all" type="checkbox"&gt;&lt;/th&gt;
                      &lt;th&gt;Email&lt;/th&gt;
                      &lt;th&gt;Full Name&lt;/th&gt;
                  &lt;/tr&gt;
              &lt;/thead&gt;
          &lt;/table&gt;
          &lt;p&gt;Press &lt;b&gt;Submit&lt;/b&gt; to add selected users to user group.&lt;/p&gt;
              &lt;p&gt;&lt;button&gt;Submit&lt;/button&gt;&lt;/p&gt;
  
              &lt;pre id="example-console"&gt;&lt;/pre&gt;
          &lt;/form&gt;
  </code></pre>