Uncheck Parent Nodes When a Child Node Is Unchecked

Uncheck Parent Nodes When a Child Node Is Unchecked

I want to do as follows with the jQuery code below

When we select a parent node then all the associated Child node will be selected.
When any Child node is Unchecked the associated parent node will be Unchecked automatically.
When the Unchecked Child node is checked the associated parent node will be checked back automatically.
  1. (function ($) {
  2.     function Tree() {
  3.         var $this = this;

  4.         function treeNodeClick() {
  5.             $(document).on('click', '.tree li a input[type="checkbox"]', function () {
  6.                 $(this).closest('li').find('ul input[type="checkbox"]').prop('checked', $(this).is(':checked'));
  7.             }).on('click', '.node-item', function () {
  8.                 var parentNode = $(this).parents('.tree ul');
  9.                 if ($(this).is(':checked')) {
  10.                     parentNode.find('li a .parent').prop('checked', true);
  11.                 } else {
  12.                     var elements = parentNode.find('ul input[type="checkbox"]:checked');
  13.                     if (elements.length == 0) {
  14.                         parentNode.find('li a .parent').prop('checked', false);
  15.                     }
  16.                 }
  17.             });
  18.         };

  19.         $this.init = function () {
  20.             treeNodeClick();
  21.         }
  22.     }
  23.     $(function () {
  24.         var self = new Tree();
  25.         self.init();
  26.     })
  27. }(jQuery))