![](/img/trans.png)
[英]Count the number of checked check-boxes in multiple panels and show the relevant number in the correct panel using jQuery/JavaScript
[英]Count the number of checked check-boxes and display them on a fixed div using jQuery
我正在嘗試編寫一個jQuery腳本(我之前從未寫過一個,我需要幫助)。 詳情如下; 我有一個帶復選框的表格。 每個復選框都有不同的ID和名稱,我將根據自己的編程原因進行操作。 我只想要計算復選框的數量,只需在固定的div中右側顯示它。 只有在勾選第一個復選框后才能顯示div。 我怎樣才能做到這一點? 我的示例復選框是:
<input type="checkbox" name="check_box_no_2" id="check_box_no_2" value="some_important_value">
復選框名稱是增量的。 意思是下一個將是check_box_no_3。 請幫忙...
到目前為止,我一直在擺弄
$("input[type=checkbox][checked]").each(
function() {
// Insert code here
}
);
但這似乎不適用於FireFox。
要選中選中的復選框,您需要:checked
psuedo-class。 您還需要觀察每個復選框,並在其設置更改時更新計數並顯示或隱藏div。 這是一種方法:
$(document).ready(function () {
$("input[type=checkbox]").each(function () {
$(this).change(updateCount);
});
updateCount();
function updateCount () {
var count = $("input[type=checkbox]:checked").size();
$("#count").text(count);
$("#status").toggle(count > 0);
};
});
其中#count
是顯示計數的元素(可能是段落標記),而#status
是要顯示/隱藏的div。
完整的HTML示例,供參考:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("input[type=checkbox]").each(function () {
$(this).change(updateCount);
});
updateCount();
function updateCount () {
var count = $("input[type=checkbox]:checked").size();
$("#count").text(count);
$("#status").toggle(count > 0);
};
});
</script>
</head>
<body>
<ul>
<li><input type="checkbox"> One</li>
<li><input type="checkbox"> Two</li>
<li><input type="checkbox"> Three</li>
</ul>
<div id="status">
<p id="count">0</p>
</div>
</body>
</html>
嘗試這個:
var totalChecked = 0;
$("input[type=checkbox]:checked").each(function(){
totalChecked++;
});
if(totalChecked > 0){
$("div.display").css("display,block");
$("div.display").text(totalChecked);
}else{
$("div.display").css("display,none");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.