<分区>
标签 javascript jquery html css
<分区>
我只想找到选中复选框的长度
。
在我的 CodePen
中,我创建了示例引用,我可以在单击 check box
时找到长度,我真正看到的是单击ALL input
check box
,所有的checkbox都要被选中。
例如:当click (or) checked
rose input check box时,length的结果显示为1
,所以当我们click (or) click (or) ) checked
All input check box
预期的结果应该是4
,点击All check box
时输入 rose, white, blue
需要勾选。
当点击一个输入复选框时其他复选框需要被选中怎么办?
HTML:
<div id="checkboxlength" class="css">
<div class="blue">
<input type="checkbox"><span>All</span>
</div>
<div>
<input type="checkbox" ><span>rose</span>
</div>
<div>
<input type="checkbox" ><span>blue</span>
</div>
<div>
<input type="checkbox"><span>white</span>
</div>
<div class="green">
<span id="count-checked-checkboxes">0</span> checked
</div>
</div>
Java 脚本:
$(document).ready(function(){
var $checkboxes = $('#checkboxlength input[type="checkbox"]');
$checkboxes.change(function(){
var countCheckedCheckboxes = $checkboxes.filter(':checked').length;
$('#count-checked-checkboxes').text(countCheckedCheckboxes);
$('#edit-count-checked-checkboxes').val(countCheckedCheckboxes);
});
});
编号:
checkboxlength
结果代码:
<div>
<span id="count-checked-checkboxes">0</span> checked
</div>
最佳答案
您可以将Id
或class
添加到check all
复选框,这样您可以在计算选中的复选框时消除它,并且在单击时也会检测到它,因此您可以选中/取消选中其他复选框。
var $checkboxes = $('#checkboxlength input[type="checkbox"]');
$checkboxes.change(function(){
/*if the clicked checkbox has check_all id
then check all other checkboxes if this one is checked
and vise versa */
if($(this).is("#check_all"))
$checkboxes.prop('checked',$(this).prop('checked'));
$('#count-checked-checkboxes').text($checkboxes.filter(':checked').length);
});
.css{
display:flex;
justify-content:center;
align-items:center;
flex-direction:column;
}
.green{
color:red;
}
.blue{
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="checkboxlength" class="css">
<div class="blue"><input type="checkbox" id="check_all"><span>All</span></div>
<div><input type="checkbox" ><span>rose</span></div>
<div><input type="checkbox" ><span>blue</span> </div>
<div><input type="checkbox"><span>white</span> </div>
<div class="green"><span id="count-checked-checkboxes">0</span> checked</div>
</div>
关于javascript - 如何找到复选框选中输入的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46171121/