首页 > 解决方案 > Jquery:在动态类下查找复选框

问题描述

我有一个动态表格,下面是结构

  1. is_required 类被添加到父类

  2. checkboxes_required 确实将所有复选框包装在 is_required 下,如下所示

       <div class="form-group is_required">
       <label>your interestes</label><br>
       <div class="checkboxes_required">
          <input type="checkbox" name="your_interestes[]" value="Games">Games 
          <input type="checkbox" name="your_interestes[]" value="study">study 
          <input type="checkbox" name="your_interestes[]" value="programming">programming
          <input type="checkbox" name="your_interestes[]" value="work">work
       </div>
    </div>
    

我可以循环 is_required 然后找到下面的 checkboxes_required 但不知道如何将其作为选择器传递以进一步循环复选框

 $(".is_required").each(function() {
        var element = $(this);          
        $(element).children().each(function () {
             if($(this).hasClass("checkboxes_required")){
            var checkboxElement = $(this);//here i have access to the div holding checkboxes 
     }
   }

下面的代码在复选框上循环,但我不确定如何将选择器传递给这个

$($("selector here ", checkboxElement).each(function(e){
  console.log(e);
  if($(this).is(":checked")){
     console.log(boolcount+"true");
  }
else {
  console.log(boolcount+"flase");
  }
})

标签: javascripthtmljquery

解决方案


为什么不直接访问所需的复选框?

这是一个简单的例子来理解我的建议,它只是自动检查它们:

$(".checkboxes_required").each(function() {
     $(this).children().each(function () {
           $(this).attr("checked", true);
     });
});

您可以使用相同的逻辑进行其他操作(只需将您的示例代码作为开始):

var checkedCount = 0;
var uncheckedCount = 0;
$(".checkboxes_required").each(function () {
    $(this).children().each(function () {
        if ($(this).is(":checked")) {
            checkedCount++;
        } else {
            uncheckedCount++;
        }
    });
});
console.log("A total of " + checkedCount + " checked");
console.log("and of " + uncheckedCount + " unchecked");

推荐阅读