Get row values from select all checkbox

I am using a script that is retrieving the values from single checked boxes but would like to create a select all checkbox and retrieve the row values of all check boxes. I have posted the code I am using and would be grateful if someone could help me to modify it to work with a selectall checkbox. Many thanks

HTML

<table cellspacing="0" class="display stripe" id="nirqst" width="100%">
  <!--        <caption>New Intake Requests</caption>-->
  <thead>
    <tr>
      <th style='width: 4%;'>ID#</th>
      <th><input type="checkbox" id="select_all" name="select_intake" /></th>
      <th>Service</th>
      <th>Activity</th>
      <th>Dept</th>
      <th>Company</th>
      <th>Address</th>
      <th>User</th>
      <th>Box#</th>
      <th>Destroy Date</th>
      <th>Request Date</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

JQUERY

$(function() {

  info = [];
  
  $(document).on('click', '.rowChk', function () {
        
    if ($('.rowChk').is(':checked')) {
    $('#rowClk').show();

    currentRows = $(this).closest("tr");
    rackid = currentRows.find("td:eq(0)").html();
//    rackidnumber = currentRows.find("td:eq(1)").html();
    rackservice = currentRows.find("td:eq(2)").html();
    rackactivity = currentRows.find("td:eq(3)").html();
    rackdept = currentRows.find("td:eq(4)").html();
    rackcompany = currentRows.find("td:eq(5)").html();
    rackaddress = currentRows.find("td:eq(6)").html();
    rackuser = currentRows.find("td:eq(7)").html();
    rackitem = currentRows.find("td:eq(8)").html();
    rackddate = currentRows.find("td:eq(9)").html();
    rackdate = currentRows.find("td:eq(10)").html();


    data = {};

    data.id = rackid;
//    data.idnumber = rackidnumber;
    data.service = rackservice;
    data.activity = rackactivity;
    data.dept = rackdept;
    data.company = rackcompany;
    data.address = rackaddress;
    data.user = rackuser;
    data.item = rackitem;
    data.intakedate = rackdate;
    data.destroydate = rackddate;

    info.push(data);
    console.log(data);


    } else {
      info.length = 0;
      $('#rowClk').css('display','none');
    }
  });
});
  
$(function () {
      
  $(document).on('click', '#rowClk', function () {

    jsonString = JSON.stringify(info);
    $("#rack").dialog("open");
    
    //console.log(jsonString);
    //$("#rack").dialog("open");
  });
});

Hi @poorbaldrick, there are no checkboxes other than the #select_all, but I suppose you might just loop over your checkboxes and run the code from your click handler…

$('tbody .rowChk').each(function () {
  this.checked = true
  // ... run code from click handler here (you might want to extract
  // that code to a reusable named function which you just call here)
})

// Or, quick and dirty:
$('tbody .rowChk').each(function () {
  if (!this.checked) {
    this.click()
  }
})

BTW you forgot the var declarations for all your variables, which implicitly defines them on the global window object (and would throw a reference error in strict mode). Also note that you can actually define properties directly on the object literal:

info.push({
  id: rackid
  service: rackservice
  // ...
})

Hi m3g4p0p

Thanks for reply. I had to shoot out urgently so didn’t have time to post the code for the checkboxes. I am using DataTables 1.10 and am using the following code to create the check boxes.

{ data: null, 'width': '20', render: function (data, type, row, meta)
        {
            if (type === 'display')
            {
                data = '<input type="checkbox" class="rowChk" name="rowChk[]" />';
            }
            return data;
        } 
      },

And the code for the rowClk button. 

"fnDrawCallback": function()
     {
        $("#nirqst_info").append("<input style='float:left; margin-right: 17px; display:none;' type='button' id='rowClk' value='Action'>");
     },

When you say run the code from click handler here, would that be the code I posted originally.

Many thanks

Yes, at least the part where you populate the data from the markup (which BTW seems a bit the wrong way round – since you’re using datatables, don’t you already have the data available anyway?).

I have managed to check all the boxes and retrieve the data from the select all checkbox. What I am having trouble with is unchecking single checkboxes from the ticked checkboxes. So what I need is a select all to retrieve data(working) and then an option for a user to remove the row from the table and only return the data for the ticked boxes.

I have posted the code I am using for the working select all and would be grateful if you could help me modify to reflect changes I have mentioned. Many thanks.

Working select all script

$(function() {
$('#select_all').change(function(){
    var cells = tableni.cells( ).nodes();
    $( cells ).find(':checkbox').prop('checked', $(this).is(':checked'));
    //console.log(cells);
//
  info = [];
  
  //$(document).on('click', '.rowChk', function () {
        
    if ($('#select_all').is(':checked')) {
    $('#rowClk').show();
      
    $('tbody .rowChk').each(function () {
    this.checked = true;
  
    var currentRows = $(this).closest("tr");
    var rackid = currentRows.find("td:eq(0)").html();
//    rackidnumber = currentRows.find("td:eq(1)").html();
    var rackservice = currentRows.find("td:eq(2)").html();
    var rackactivity = currentRows.find("td:eq(3)").html();
    var rackdept = currentRows.find("td:eq(4)").html();
    var rackcompany = currentRows.find("td:eq(5)").html();
    var rackaddress = currentRows.find("td:eq(6)").html();
    var rackuser = currentRows.find("td:eq(7)").html();
    var rackitem = currentRows.find("td:eq(8)").html();
    var rackddate = currentRows.find("td:eq(9)").html();
    var rackdate = currentRows.find("td:eq(10)").html();


    data = {};

    data.id = rackid;
//    data.idnumber = rackidnumber;
    data.service = rackservice;
    data.activity = rackactivity;
    data.dept = rackdept;
    data.company = rackcompany;
    data.address = rackaddress;
    data.user = rackuser;
    data.item = rackitem;
    data.intakedate = rackdate;
    data.destroydate = rackddate;

    info.push(data);
    //console.log(data);
});
    } 
//    else if ($('.rowChk').is(':checked')) {
//    $('#rowClk').show();
//    } 
//    else
//    {
//      info.length = 0;
//      $('#rowClk').css('display','none');
//      
//    }
//});
});
});

The simplest way would be to clear the data and populate it anew, but only from the rows with checked checkboxes…

$('tbody .rowChk:checked').each(/* ... */)

… but more efficient would be to find the index of the data entry with the current ID, and remove that entry; or you filter the data to the entries that don’t have the current ID.

Could you provide example based on my code please. I am fairly new to js and not sure where I should put this. Thanks

When clicking a checkbox, you’re pushing the data if it is checked, otherwise you’re clearing the entire data; but instead, you’d filter the data in the else block (or re-populate it):

if ($('.rowChk').is(':checked')) {
  // Pushing data to info here...
} else {
  info.length = 0
  // ^ Replace this line with the code filtering or re-populating the data
}

PS: That $('.rowChk').is(':checked') condition doesn’t seem quite right as it always checks the first checkbox, not the one currently being clicked – try this instead:

if (this.checked) {
  // ...
}

ok. Still not usre how to piece all this together but I shall try based on all the help you have given me. lastly, how do I re-populate the data? Thanks

Basically like you did when selecting all rows, just only for those that are checked. But I’d suggest to get the data directly from the datatables API, rather than reading it from the DOM that was actually generated by datatables (or is already present, at any rate)… along the following lines:

var $table = $('#my-table')

var api = $table.DataTable({
  // ...
})

var getInfo = function () {
  var $selected = $table.find(':checked').closest('tr')
  return api.rows($selected).data()
}

// At some point do something with the data
console.log(getInfo())

Here’s a simple demo how to use it with checkboxes to select rows:

https://codepen.io/m3g4p0p/pen/MWgZVYX

Thanks for that. Do i use this as new code ie; replace my original code? or do I need to use this code in place of my original datatable code? thanks

I’d go for option 4, none of the above.

The code is intended to give you an idea of how it might work, when other needed parts are put in place too.

1 Like

Which code do you mean specifically? The getInfo() function should work with your code in place of the “manual” data population from the DOM (you’d probably have to adjust the $table reference / selector though); the codepen is just supposed to be an example though and won’t work as a drop-in replacement for your original code.

The important part is indeed using the datatables API here as it greatly simplifies your code. So just try to apply this to your code while consulting the docs; if you have trouble understanding certain bits I’ll of course try to help as well. :-)

(x-post)

Thanks very much for all your help.

Sorry Paul. What is option 4? Thanks

Option 4 is something that wasn’t considered, that the code can not and does not work all by itself, because there is more that you need to do to it to get it working.

On a simpler level. With the updated code I have posted, I can add to array fine but how do I remove from array if checkbox is unticked. I feel this would be simpler. Any help would be greatfully appreciated. Many thanks

$(function() {
info = [];
  
  $(document).on('click', '.rowChk', function () {
        
    if($(this).is(':checked')) {
    $('#rowClk').show();

    var currentRows = $(this).closest("tr");
    var rackid = currentRows.find("td:eq(0)").html();

    data = {};

    data.id = rackid;

    info.push(data);
    //console.log(data);
    //console.log(info.length);
    } else {
        delete [info.id];  <--- Need to delete checkbox value from array -->
        //console.log(info.length);
        if(info.length === 0) {
        $('#rowClk').css('display','none');
        }
    }
 });
});

Please check the docs on the MDN, that’s not how the delete operator works. But you wouldn’t delete an array element anyway as this leaves an uńdefined “hole”; better find the index of the element to remove, and then splice the array at that position; or filter the array to those elements that don’t have the given ID:

var info = [{ id: 'foo' }, { id: 'bar' }]
var rackid = 'foo'

var index = info.findIndex(function (item) {
  return item.id === rackid
})

if (index !== -1) {
  info.splice(index, 1)
}

// Or:

info = info.filter(function (item) {
  return item.id !== rackid
})

Many thanks. Really helping me to get to grips with arrays and objects. I do have one question though. In my local code I am capturing data from rows in a table. When I click a checkbox, the data is returned thus in console.

What I am trying to do is remove an item from the array if the checkbox is unticked. The last example that you posted works fine, but how do I remove from array based on id? I posted my code originally and have tried to adapt your code to mine but instead of deleting from array, it still leaves the data in the array even if the checkbox is unticked. How do I modify thi to work with my code. Many thanks for all your help.

[{"id":"33","service":"Standard","activity":"New Box Intake","dept":"DEMO44","company":"DEMO","address":"22 London Road  Charles House   London W12 3RT ","user":"Demo User","item":"DEMO11122","intakedate":"22/09/2019 09:48:41","destroydate":"28/09/2019"},
{"id":"34","service":"Standard","activity":"New Box Intake","dept":"DEMO44","company":"DEMO","address":"22 London Road  Charles House   London W12 3RT ","user":"Demo User","item":"DEMO6423","intakedate":"22/09/2019 09:48:41","destroydate":"28/09/2019"}]

Here’s an example object that’s being worked on:

var info = [
  {
    "id":"33","service":"Standard","activity":"New Box Intake","dept":"DEMO44",
    "company":"DEMO","address":"22 London Road Charles House London W12 3RT ",
    "user":"Demo User","item":"DEMO11122",
    "intakedate":"22/09/2019 09:48:41","destroydate":"28/09/2019"
  },
  {
    "id":"34","service":"Standard","activity":"New Box Intake","dept":"DEMO44",
    "company":"DEMO","address":"22 London Road Charles House London W12 3RT ",
    "user":"Demo User","item":"DEMO6423",
    "intakedate":"22/09/2019 09:48:41","destroydate":"28/09/2019"
  }
];

And you want to know how to remove an item based on the id.

You can use a filter, that keeps the item on a truthy value and removes it on a falsy value.

function removeItem(info, idToRemove) {
    return info.filter(function (item) {
        return item.id !== idToRemove;
    });
}
...
info = removeItem(info, "33");