TreeGrid how to check/uncheck all child sublevels checkboxes when marks parent

会有一股神秘感。 提交于 2019-12-03 16:35:13

First of all I recommend you don't place HTML fragments inside of JSON data. One can use custom formatter to include checkboxes inside of grid cells:

formatter: function (cellvalue) {
    return "<input type='checkbox' class='itmchk' ><strong>" +
        $.jgrid.htmlEncode(cellvalue) + "</strong>";
}

To control checking/unchecking of the checkboxes you can use beforeSelectRow callback of the grid. jqGrid bound internally click event to the grid body. So is no event handler exists directly on the element the event bubbling take place. It allows to catch checking/unchecking of any checkboxes inside of one beforeSelectRow callback. Inside of beforeSelectRow you should first test whether it was click on a checkbox which you want to control.

Callback beforeSelectRow has two parameters: rowid and the event object. The property target of the event object will be the DOM element which was clicked by user. Because you add your custom itmchk class to every such checkboxes it will be enough to verify the class on the clicked element.

The next problem is that many jqGrid method which works with TreeGrid like getNodeChildren has record as the input parameter, but you have only rowid instead. jqGrid save loaded items of the grid locally. So the simplest way to get record from the rowid is to use getLocalRow method.

As the result the code of beforeSelectRow callback could be the following:

beforeSelectRow: function (rowid, e) {
    var $this = $(this),
        isLeafName = $this.jqGrid("getGridParam", "treeReader").leaf_field,
        localIdName = $this.jqGrid("getGridParam", "localReader").id,
        localData,
        state,
        setChechedStateOfChildrenItems = function (children) {
            $.each(children, function () {
                $("#" + this[localIdName] + " input.itmchk").prop("checked", state);
                if (!this[isLeafName]) {
                    setChechedStateOfChildrenItems($this.jqGrid("getNodeChildren", this));
                }
            });
        };
    if (e.target.nodeName === "INPUT" && $(e.target).hasClass("itmchk")) {
        state = $(e.target).prop("checked");
        localData = $this.jqGrid("getLocalRow", rowid);
        setChechedStateOfChildrenItems($this.jqGrid("getNodeChildren", localData), state);
    }
}

It's important to mention that children checkboxes will be checked/unchecked only on previously loaded items. Because you load the data of the grid at once and use loaded: true property then it's not problem for you.

The corresponding demo shows that the above code really works. It's modification of the demo which I created by answering on your previous question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!