用于获取div中已选中复选框的数量的函数

时间:2016-12-14 11:42:08

标签: jquery

我正在尝试创建一个JQuery函数,该函数将获取特定div中已检查的复选框的数量,该复选框作为参数传递。

var max = 1;
function checkMax(e) {   
    var item = $("#" + e).html().find("input:checked");
    var checked = item > ":input:checked";   

    alert(item);    
}

if (item >= max){
preventDefault();
}

如果已经检查了允许的最大复选框数,如何阻止用户检查复选框

3 个答案:

答案 0 :(得分:2)

使用:checked获取.find()元素,然后使用length属性。

var item = $("#" + e).find("input:checked");
alert(item.length);  

无需使用.html()

答案 1 :(得分:0)

根据OP的要求,我创建了一个功能接受一个元素并检查内容的复选框。以简单的方式,您可以使用单个选择器:

$(function () {
  $("a").click(function () {
    checkHowMany($(this).closest("div"));
    return false;
  });
  function checkHowMany($div) {
    var num = $div.find(".chk-box:checked").length;
    alert("There are " + num + " checked check boxes.");
  }
});
* {font-family: 'Segoe UI';}
label {display: block;}
div {margin-bottom: 10px;}
a {display: inline-block; text-decoration: none; padding: 5px; border: 1px solid #ccc; border-radius: 3px; color: #000;}
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<div class="section-1">
  <label><input type="checkbox" class="chk-box"> Check Me</label>
  <label><input type="checkbox" class="chk-box"> Check Me</label>
  <label><input type="checkbox" class="chk-box"> Check Me</label>
  <label><input type="checkbox" class="chk-box"> Check Me</label>
  <a href="">Check how many checked in this Section.</a>
</div>
<div class="section-2">
  <label><input type="checkbox" class="chk-box"> Check Me</label>
  <label><input type="checkbox" class="chk-box"> Check Me</label>
  <label><input type="checkbox" class="chk-box"> Check Me</label>
  <label><input type="checkbox" class="chk-box"> Check Me</label>
  <a href="">Check how many checked in this Section.</a>
</div>
<div class="section-3">
  <label><input type="checkbox" class="chk-box"> Check Me</label>
  <label><input type="checkbox" class="chk-box"> Check Me</label>
  <label><input type="checkbox" class="chk-box"> Check Me</label>
  <label><input type="checkbox" class="chk-box"> Check Me</label>
  <a href="">Check how many checked in this Section.</a>
</div>

这里,<a>调用函数及其父<div>作为要传递给函数的参数。

答案 2 :(得分:0)

检查出来 -

$("#btn1").click(function() {
  getCheckedLength("container1")
});

$("#btn2").click(function() {
getCheckedLength("container2")
});

function getCheckedLength(id) {
  var $div = $("#" + id);
  alert($("input[type='checkbox']:checked", $div).length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="container1">
  <input type="checkbox">1 &nbsp;&nbsp;
  <input type="checkbox">2 &nbsp;&nbsp;
  <input type="checkbox">3 &nbsp;&nbsp;
</div>

<div id="container2">
  <input type="checkbox">4 &nbsp;&nbsp;
  <input type="checkbox">5 &nbsp;&nbsp;
  <input type="checkbox">6 &nbsp;&nbsp;
</div>

<input type="button" id="btn1" value="Get checked number form div 1">
<input type="button" id="btn2" value="Get checked number form div 2">