Simple example of jquery simulating multilevel checkbox effects

  • 2021-06-28 08:23:44
  • OfStack

Today I've experienced the power of jquery again, making a multi-level check box effect, the total code is 20 + lines on over.

I would like to use js to do a look, just write a few methods will not work, compatibility needs to be considered a lot, and the amount of code has gone up sharply.

Share this implementation of jquery.The code block is divided into two blocks:

1 is the effect of full selection, that is, when you click the check box of full selection, its descendants are either selected or unchecked accordingly.This is a good job, the code is as follows:


evtEle.parent().next(".checks").find("input:checkbox").attr("checked", evtEle[0].checked);//evtEle Is Clicked Checkbox 

2 is the parent box of the current check box, which determines whether the parent box is selected based on whether all the siblings of the current box are selected, and continues to look up at the parent box, etc.
When all is checked, the implementation here uses parents to get all the parent boxes, which are combined with each for each operation.

When not all selected, the parent box loses being selected in turn.The code is as follows:


if (evtEle.is("input:checked")) {
          evtEle.parents(".checks").each(function () {
            !$(this).children("p").children("input:checkbox").filter(function () {
              return !this.checked;
            })[0] && $(this).prev().children("input:checkbox").attr("checked", "checked");
          });
        } else {
          evtEle.parents(".checks").prev().children("input:checkbox").attr("checked", false);
        }

Related articles: