jQuery代码获取复选框长度,而使用jQuery数据表

jQuery code to get checkbox length while using jQuery DataTables

本文关键字:jQuery 数据表 代码 获取 复选框      更新时间:2023-09-26

我得到错误的值,而获取的复选框长度使用jQuery和jQuery数据表

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

分页时,只选择12个值。在警报中,它只显示2当我保持在2页和测试。

原因

jQuery数据表只存在于DOM中可见的行。这就是为什么使用jQuery $()方法访问复选框会给你2个节点。

解决方案

要选择复选框,包括DOM中不存在的复选框,并考虑到当前的搜索查询,使用下面的代码:

// 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);

您需要在所有单击事件处理程序中使用此逻辑:$('.chkSelectAll').click, $('.Projection_test').click$('#FavouriteList').click

指出

jQuery DataTables也有$()方法,允许在完整的表上执行jQuery选择操作。但是,它不允许过滤掉应用了搜索的行。

请参阅我们的文章jQuery数据表-如何添加复选框列,了解更多使用jQuery数据表时如何使用复选框的信息。