列表中的多个复选框

时间:2018-02-08 09:48:24

标签: jquery html

我列出了每个列表项中都有一个复选框的列表。我希望如果选中列表项中的任何一个子复选框,则也会选中父复选框。

HTML:

set hive.cli.print.header=true;

4 个答案:

答案 0 :(得分:0)

试试这可能对你有所帮助......

$(function () {
    $("li:has(li) > input[type='checkbox']").change(function () {
        $(this).siblings('ul').find("input[type='checkbox']").prop('checked', this.checked);
    });
    $("input[type='checkbox'] ~ ul input[type = 'checkbox']").change(function () {
        $(this).closest("li: has(li)").children("input[type = 'checkbox']").prop('checked', $(this).closest('ul').find("input[type = 'checkbox']").is(':checked'));
    });
});

答案 1 :(得分:0)

$('.child').change(function() {
    var allChild=$('.child');
    var check=false;
    $.each(allChild).function(i,child){
      if($(this).is(":checked")) {
           check=true;
      }
    }
    $('#parent').attr("checked", check);           
});

试试这个

答案 2 :(得分:0)

定义一个JavaScript函数,将子元素与父元素链接起来:

function checkParent(parentId, childId) {
  document.getElementById(parentId).checked = document.getElementById(childId).checked;
}

然后在单击子元素时调用该函数:

<input type="checkbox" id="parent">
<ul>
  <li><input id="childOne" type="checkbox" class="child" onclick="checkParent('parent', 'childOne')"></li>

  <li><input id="childTwo" type="checkbox" class="child" onclick="checkParent('parent', 'childTwo')"></li>
 </ul>

请注意,我也将id添加到子元素中。

答案 3 :(得分:0)

这个有两种方式。检查父盒子时将检查孩子,如果您需要,我认为这是有道理的。 https://jsfiddle.net/5bea6Lty/

var count = 0;
$('#parent').change(function() {
    $('.child').prop('checked', $(this).is(':checked')).change();
});
$('.child').change(function() {
    if ($(this).is(':checked'))
    count++;
  else
    count--;
  $('#parent').prop('checked', (count <= 0) ? 0 : 1);
});
相关问题