我正在尝试创建一个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();
}
如果已经检查了允许的最大复选框数,如何阻止用户检查复选框
答案 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
<input type="checkbox">2
<input type="checkbox">3
</div>
<div id="container2">
<input type="checkbox">4
<input type="checkbox">5
<input type="checkbox">6
</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">