manojgolty manojgolty - 1 year ago 76
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.

HTML:


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


JavaScript:

$('#dataTables-show-productList').DataTable({
width:'100%'
, 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');

alert($('.Projection_test:checked').length);
e.preventDefault();
});


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

CAUSE

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

SOLUTION

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' })
   .nodes();

// 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.

NOTES

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