设置复选框选择范围的限制

To set limit over selection of Checbox

本文关键字:范围 复选框 选择 设置      更新时间:2023-09-26

我有2个div容器,都包含Checkbox元素。我想用一个极限从DIV2最多可以选择7个复选框,从DIV1用户可以选择所有复选框。但是,DIV1和DIV2中的复选框总数不应超过10个。

每次在选中/取消选中时,选中的复选框计数为10,然后剩余未选中的复选框将被禁用。

<div id="main DIV">
    <div id="DIV1">
        <input type="checkbox" checked/>1 
        <input type="checkbox" checked/>2 
        <input type="checkbox" checked/>3<br/>
        <input type="checkbox" checked/>4 
        <input type="checkbox" checked/>5 
    </div>
    <div id="DIV2">
        <input type="checkbox" checked/>1 
        <input type="checkbox" checked/>2 
        <input type="checkbox" checked/>3<br/>
        <input type="checkbox" checked/>4 
        <input type="checkbox" checked/>5 
        <input type="checkbox" checked/>6
        <input type="checkbox" checked/>7
        <input type="checkbox" checked/>8
        <input type="checkbox" checked/>9
    </div>
</div>

var div2Cbs = $("#DIV2 :checkbox");
var allCbs = div2Cbs.add("#DIV1 :checkbox").on("click", function() {
  var disable2 = div2Cbs.filter(":checked").length >= 7;
  var disableAll = allCbs.filter(":checked").length >= 10;
  allCbs.filter(":not(:checked)").prop("disabled", disableAll);
  div2Cbs.filter(":not(:checked)").prop("disabled", disable2 || disableAll);
});
  
div { border: thin black solid; margin: 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="DIV1">
<input type="checkbox"/>1 
  <input type="checkbox"/>2 
  <input type="checkbox"/>3<br/>
  <input type="checkbox"/>4 
  <input type="checkbox"/>5 
</div>
<div id="DIV2">
<input type="checkbox"/>1 
  <input type="checkbox"/>2 
  <input type="checkbox"/>3<br/>
  <input type="checkbox"/>4 
  <input type="checkbox"/>5 
 <input type="checkbox"/>6
 <input type="checkbox"/>7
 <input type="checkbox"/>8
 <input type="checkbox"/>9
</div>

试试

//Give you the length of the checked chechbox under `mainDIV`
$('#mainDIV input[type="checkbox"]:checked').length

请确保,ID不应有空格。用mainDIV代替main DIV

  • 在Jquery中使用parent child选择来提供限制。
  • :checked:not(:checked)将帮助您实现这一点。