如果未选中子节点,则取消选中父级

时间:2015-03-26 12:40:58

标签: javascript jquery checkbox

如果取消选中其中一个子节点,我在未经检查的父节点上遇到问题。但我试图搜索解决方案,但没有一个解决方案适用于我的代码。

我在这里引用嵌套复选框功能http://uoziod.github.io/deep-checkbox/

以下是我的代码示例:

<ul>
    <li>
        <label><input type="checkbox" data-id="All Master" data-name="All Master" id="myCheckBox0" onchange="checkDisabled(testing);"/> All Kedai Kiosk On Master Mode</label>
        <ul>

            <li>
                <label><input type="checkbox" data-id="Terengganu" data-name="Terengganu" id="myCheckBox76" onchange="checkDisabled(testing);"/> Terengganu</label>
                <ul id="navlist">
                    <li><label><input type="checkbox" data-id="Kiosk 63" data-name="Kiosk 63" id="myCheckBox77" onchange="checkDisabled(testing);"/> Kiosk 63</label></li>
                    <li><label><input type="checkbox" data-id="Kiosk 64" data-name="Kiosk 64" id="myCheckBox78" onchange="checkDisabled(testing);"/> Kiosk 64</label></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

我想要的是当我取消选中自助终端63时,父母的登嘉楼也将被取消选中。我使用的是从网站上下载的jquery.deepcheckbox.js。我应该改变什么才能实现这一目标?感谢

编辑: 我在这里复制javascript代码。它有什么我需要改变才能实现父取消检查功能?感谢

代码在这里:

(function ($) {
  var defaults = {
      listItemBefore: '<span class="item">',
      listItemAfter: '</span>',
      listItemsDivider: ', ',
      labelExceptBefore: ' (except ',
      labelExceptAfter: ')',
      labelExceptBetween: ', ',
      labelNothingIsSelected: 'Nothing is selected'
    },
    instances = [];

  $.fn.deepcheckbox = function (options) {
    if (instances.indexOf(this.selector) < 0) {
      var tree = _buildTree(this);
      _bindCheckboxes(tree, function (item, value) {
        if (item.children) {
          _setValueToChildren(item.children, value);
        }
      });

      if (!options) {
        options = {};
      }

      options = $.extend(defaults, options);

      if (options.readableListTarget) {
        $(options.readableListTarget).html(options.labelNothingIsSelected);

        _bindCheckboxes(tree, function () {
          var items = [],
            except = [],
            output = [];

          function _dig (branch, level, skipAdding) {
            if (!level) {
              level = 0;
            }

            for (var i = 0, len = branch.length; i < len; i++) {
              if (branch[i].el.prop('checked')) {
                var value = options.listItemBefore.replace('{{id}}', branch[i].el.data('id')) + branch[i].el.data('name'),
                  exceptCount = 0;

                if (branch[i].children) {
                  for (var j = 0, lenJ = branch[i].children.length; j < lenJ; j++) {
                    if (!branch[i].children[j].el.prop('checked')) {
                      except.push(branch[i].children[j].el.data('id'));
                      if (exceptCount === 0) {
                        value += options.labelExceptBefore;
                      }
                      if (exceptCount > 0) {
                        value += options.labelExceptBetween;
                      }
                      value += branch[i].children[j].el.data('name');
                      exceptCount++;
                    }
                  }
                  if (exceptCount > 0) {
                    value += options.labelExceptAfter;
                  }
                }

                value += options.listItemAfter;

                if (level > 0 && branch[i].el.prop('checked') && !branch[i].parent.prop('checked')) {
                  skipAdding = false;
                }

                if (!skipAdding || exceptCount > 0) {
                  output.push(value);
                  items.push(branch[i].el.data('id'));
                }
              }

              if (branch[i].children) {
                _dig(branch[i].children, level + 1, true);
              }
            }
            return output.join(options.listItemsDivider);
          }

          var digged = _dig(tree);
          $(options.readableListTarget).html((digged.length > 0) ? digged : options.labelNothingIsSelected);

          if (options.onChange && typeof options.onChange === 'function') {
            options.onChange(items, except);
          }
        });
      }

      instances.push(this.selector);
    }
  };

  function _buildTree ($anchor, $parent) {
    var output = [],
      rootItems = $anchor.find('ul:first > li');

    for (var i = 0, len = rootItems.length; i < len; i++) {
      var $element = $(rootItems[i]).find('input[type=checkbox]:first'),
        id = _guId();

      if (!$element.data('id')) {
        $element.data('id', id);
      }

      if (!$element.data('name')) {
        $element.data('name', id);
      }

      var branch = {
          el: $element
        },
        children = _buildTree($(rootItems[i]), $element);

      if (children) {
        branch.children = children;
      }

      if ($parent) {
        branch.parent = $parent;
      }

      output.push(branch);
    }

    return output.length > 0 ? output : false;
  }

  function _bindCheckboxes (tree, callback) {
    for (var i = 0, len = tree.length; i < len; i++) {
      (function (item) {
        $(item.el).on('change', function () {
          callback(item, $(this).prop('checked'));
        });

        if (item.children) {
          _bindCheckboxes(item.children, callback);
        }
      }(tree[i]));
    }
  }

  function _setValueToChildren (tree, value) {
    for (var i = 0, len = tree.length; i < len; i++) {
      tree[i].el.prop('checked', value);
      if (tree[i].children) {
        _setValueToChildren(tree[i].children, value);
      }
    }
  }

  function _guId () {
    function s4 () {
      return Math.floor((1 + Math.random()) * 0x10000)
        .toString(16)
        .substring(1);
    }

    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
  }
})(jQuery);

我的测试选择了部分:

<div>
                            <p>Selected items (readable): <span class="selected-readable"></span></p>
                            <p>Selected items: <span class="selected">[]</span></p>
                            <p>Excepted items: <span class="excepted">[]</span></p>
                        </div>

2 个答案:

答案 0 :(得分:2)

请试试这个

$('ul :checkbox').bind('click', function () {
    var $chk = $(this), $li = $chk.closest('li'), $ul, $parent ;
    if($li.has('ul')){
        $li.find(':checkbox').not(this).prop('checked', this.checked)
    }
    
    do{
        $ul = $li.parent();
        $parent = $ul.siblings(':checkbox');
        if($chk.is(':checked')){
            $parent.prop('checked', $ul.has(':checkbox:not(:checked)').length == 0)
        } else {
            $parent.prop('checked', false)
        }
        $chk = $parent;
        $li = $chk.closest('li');
    } while($ul.is(':not(.someclass)'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<ul class="parent-ul">
  <li>
    <input type="checkbox" data-id="All Master" data-name="All Master" id="myCheckBox0" onchange="checkDisabled(testing);" />All Kedai Kiosk On Master Mode
    <ul>

      <li>
        <input type="checkbox" data-id="Terengganu" data-name="Terengganu" id="myCheckBox76" onchange="checkDisabled(testing);" />Terengganu
        <ul id="navlist">
          <li>
            <input type="checkbox" data-id="Kiosk 63" data-name="Kiosk 63" id="myCheckBox77" onchange="checkDisabled(testing);" />Kiosk 63</li>
          <li>
            <input type="checkbox" data-id="Kiosk 64" data-name="Kiosk 64" id="myCheckBox78" onchange="checkDisabled(testing);" />Kiosk 64</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

答案 1 :(得分:0)

我在你的页面上测试它的工作!

    $(document).ready(function(){
    $('body').on('click', 'input[type="checkbox"]', function(){
        $this = $(this)
        var flag = true
        $.each($this.closest('ul').find('input'), function(){

            if ($(this).prop('checked') == false){
                flag = false}
        });

        if(flag){
            $this.closest('ul').closest('li').find('input').first().prop('checked', true);

            if ($this.closest('ul').closest('li').closest('ul').closest('li').length > 0){ 
                document.aa = $this.closest('ul').closest('li').closest('ul').closest('li').find('ul input')
                $.each( $this.closest('ul').closest('li').closest('ul').closest('li').find('ul input'), function(){

                    if ($(this).prop('checked') == false){
                        flag = false}
                });
                if(flag){$this.closest('ul').closest('li').closest('ul').closest('li').find('input').first().prop('checked', true);}
        }}
            else{
        parents = $this.parents('ul li');
        parents.splice(0,1);

        for (var i = 0; i < parents.length; i++) {
            $this = $(parents[i]);

            $this.find('label').first().find('input').prop('checked', false);
        };
    }

    });
});