如果未选中一个孩子,则取消选中“父母和祖父母”复选框

时间:2019-04-03 19:32:09

标签: javascript

我正在开发一个需要多个复选框的值的应用程序。我有包含复选框的嵌套列表。当前的功能是这样的:

  1. 选中父项后,所有子项都在父项下选中。
  2. 取消选中一个孩子时,所有父级stil都被选中。

我需要添加此功能:

  1. 如果在选中父级之后取消选中子级,则父级会取消选中,但将子级保留为选中状态。
  2. 取消选中孩子时,带有祖父母的父母复选框需要具有灰色背景或不确定。

JSON

operation not permitted

JavaScript

{
    "liga": [
        {
            "id": 1,
            "name": "La liga",
            "children": [
                {
                    "id": 2,
                    "name":"Barcelona",
                    "parentId": 1,
                    "children": [
                        {
                            "id": 8,
                            "name":"Barcelona B",
                            "parentId": 2
                        }
                    ]
                },
                 {
                    "id":3,
                    "name":"Real Madrid",
                    "parentId": 1
                }
            ]
        },
        {
            "id": 4,
            "name": "Bundeliga",
            "type": "dir",
            "children": [
                {
                    "id": 5,
                    "name":"Bayer",
                    "parentId": 4
                },
                 {
                    "id":6,
                    "name":"Borusia",
                    "parentId": 4
                }
            ]
        },

已解决的问题

const toogleCheckbox = (element) => {
    let treeNode = element.parentNode;
    if (treeNode) {
      treeNode.isSelected = !treeNode.isSelected;
      toggleChildren(treeNode.childNodes, treeNode.isSelected);
    }

}

const toggleChildren = (children, state) => {
    for (let i = 0; i < children.length; i++) {
      if (children[i].type == "checkbox") {
        let parent = children[i].parentNode;
        parent.isSelected = state;
        isAllSelected(parent);

        children[i].checked = state;
      }
      toggleChildren(children[i].childNodes, state);
    }
  };
const isAllSelected = node => {
    let allSelected = node.isSelected;
    for (let i = 0; i < node.childNodes.length; i++) {
      if (node.childNodes[i].type == "checkbox") {
        let parentNode = node.childNodes[i].parentNode.parentNode;
        allSelected = isAllSelected(parentNode);
      }
    }
    return allSelected;
  };

0 个答案:

没有答案