使用jQuery DataTables获取复选框长度的jQuery代码

时间:2015-08-03 10:32:18

标签: javascript jquery datatables

使用jQuery和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();
});

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

1 个答案:

答案 0 :(得分:1)

原因

使用jQuery DataTables,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 DataTables时如何使用复选框的更多信息,请参阅我们的文章jQuery DataTables – How to add a checkbox column