manojgolty manojgolty -4 years ago 130
Javascript Question

jQuery code to get checkbox length while using jQuery DataTables

I am getting wrong value while fetching the checkbox length using jQuery and jQuery DataTables.


<table class="table table-bordered" id="dataTables-show-productList">
<th width="5px"><input type="checkbox" name="Select All" class="chkSelectAll" /></th>
<th>Product Information</th>
<c:forEach var="masterListVar" items="${masterList}">
<td width="1%" align="center">
<c:if test="${masterListVar.saveFlag}">
<input type="checkbox" path="selectChecked" checked class="Projection_test" value="${masterListVar.productId}"/>
<c:if test="${!masterListVar.saveFlag}">
<input type="checkbox" path="selectChecked" class="Projection_test" value="${masterListVar.productId}"/>


, responsive : true
, "bSort" : false

$('.chkSelectAll').click(function () {
$('.Projection_test').prop('checked', $(this).is(':checked'));

$('.Projection_test').click(function () {
if ($('.Projection_test:checked').length == $('.Projection_test').length) {
$('.chkSelectAll').prop('checked', true);
else {
$('.chkSelectAll').prop('checked', false);

$('#FavouriteList').click(function (e) {
var selectedRow = $('.Projection_test');


When paginating, while selecting only 12 values. in the alert it showing only 2 when i kept in the 2 page and testing.

Answer Source


With jQuery DataTables only visible rows exist in DOM. That is why accessing checkboxes with jQuery $() method gives you 2 nodes.


To select checkboxes including those that don't exist in DOM and taking into the account current search query, use the code below:

// Select all available rows with search applied    
var rows = $('#dataTables-show-productList').DataTable()
   .rows({ 'search': 'applied' })

// Checked checkboxes
console.log($('.Projection_test:checked', rows).length);

// All checkboxes
console.log($('.Projection_test', rows).length);

You need to use this logic in all click event handlers: $('.chkSelectAll').click, $('.Projection_test').click and $('#FavouriteList').click.


jQuery DataTables also has $() method that allows to perform a jQuery selection action on the full table. However it doesn't allow to filter out rows with search applied.

See our article jQuery DataTables – How to add a checkbox column for more information on how to work with checkboxes when using jQuery DataTables.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download