繁体   English   中英

jQuery代码可在使用jQuery DataTables时获取复选框长度

[英]jQuery code to get checkbox length while using 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。

原因

使用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);

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

笔记

jQuery DataTables还具有$()方法,该方法允许对整个表执行jQuery选择操作。 但是,不允许在应用搜索的情况下过滤掉行。

请参阅我们的文章jQuery DataTables –如何添加复选框列 ,以获取有关在使用jQuery DataTables时如何使用复选框的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM