JQuery 在不同的类上运行



我正在尝试计算用户选中了多少个复选框,以便我可以禁用其他输入,以便它进入数据库。我如何使用不同类的数组$(" . ")不同的元素上运行,因为我的表单中有几组输入。

<script>
var countChecked = function() {
var n = $( ".neutral:checked" ).length;
alert( n + (n === 1 ? " is" : " are") + " checked!" );
};
countChecked();
$( "input[type=checkbox]" ).on( "click", countChecked );
</script>

// Count ALL checked boxes.
console.log($(":checked").length)
// Count checkboxes for a set of given classes.
console.log($(".one, .two, .three, .four").filter(":checked").length)
// Or given as array
let targets = [".one", ".two", ".three", ".four"];
console.log($(targets.join(",")).filter(":checked").length)
// or without the dot
targets = ["one", "two", "three", "four"];
console.log($(targets.map(x => `.${x}`).join(",")).filter(":checked").length)
// or if you want to do something separately for each class
const handleCheckboxes = (cls) => {
var n = $(`.${cls}:checked`).length;
console.log(`${n} of class ${cls} ${n === 1 ? "is" : "are"} checked!`);
// do even more stuff here
};
targets.forEach(handleCheckboxes);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="one" type="checkbox" checked>
<input class="two" type="checkbox" checked>
<input class="two" type="checkbox" checked>
<input class="two" type="checkbox" checked>
<input class="three" type="checkbox">
<input class="three" type="checkbox">
<input class="four" type="checkbox" checked>
<input class="four" type="checkbox">

您可以简单地遍历所有类

//Array
var array = ["class1", "class2", "class3", "class4", "class5"];
//Loop
array.forEach((className, classIndex) => {
var n = $('.' + className + ':checked').length;
var term = n === 1 ? "is" : "are";
console.log(n + ' of ' + className + term + ' checked');
}); 

相关内容

  • 没有找到相关文章

最新更新