D W Langham D W Langham - 6 months ago 263
jQuery Question

How to get check box input value from dataTable row collection?

I have a table that serves as a jquery dataTable. Each data row has a check box column. Visitors to the page will click the check boxes to select which items to delete. The dataTable has pagination and filtering enabled, so a visitor may select one or more check boxes on different pages. When the user clicks "delete", I want to be able to grab the value of each selected check box.

I figured out how to get the checked rows as a collection using this:

var rowcollection = oTable.$(".call-checkbox:checked", {"page": "all"});
What I haven't figured out is how to iterate through the collection to grab the value of each row's check box input.

Below is the script and the table. Please tell me I'm missing something incredibly obvious.

<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#calltable').dataTable({
"bPaginate": true,
"bLengthChange": true,
"bFilter": true,
"bSort": true,
"bInfo": true,
"bAutoWidth": true,
"bStateSave": true,
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ -1,0] }
]
});

// trashcan is the id of the icon users click to delete items
// onclick get all the checked rows and do something
$("#trashcan")
.click(function () {

var oTable = $('#calltable').dataTable();
var rowcollection = oTable.$(".call-checkbox:checked", {"page": "all"});
for(var i = 0; i < rowcollection.length; i++)
{
// GET THE VALUE OF THE CHECK BOX (HOW?) AND DO SOMETHING WITH IT.
//
}
});

});
</script>



<table id="calltable" class="pretty">
<thead>
<tr>
<th><span id="check">Check</span> |
<span id="uncheck">U</span> |
<img src="/trash_16x16.gif" alt="Delete" id="trashcan" />
</th>
<th>phone</th>
<th>name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" class="call-checkbox" value="22" />
</td>
<td>8438740903</td>
<td>Susan</td>
<td>S</td>
</tr>
<tr>
<td>
<input type="checkbox" class="call-checkbox" value="23" />
</td>
<td>9098983456</td>
<td>Jack Sparrow</td>
<td>S</td>
</tr>
</tbody>
</table>

Answer

Use the each function, instead of the for loop like this:

var oTable = $('#calltable').dataTable();
var rowcollection =  oTable.$(".call-checkbox:checked", {"page": "all"});
rowcollection.each(function(index,elem){
    var checkbox_value = $(elem).val();
    //Do something with 'checkbox_value'
});
Comments