mardi 28 avril 2015

HTML tree with tristate checkboxes to show and hide content

I have an HTML tree that has checkboxes to check and uncheck items. I found a nice working example here: http://ift.tt/1HUpc2O

Now what i want to do is use this tree to link it to content as if the tree represents the chapters of an e-book and u can tick on and off which chapters u want to see. I just can't seem to get it work right entirely with the indeterminate state of the checkboxes. If i tick a child of leather shoes it has to show the parent leather shoes too, if i tick on leather shoes, both leather shoes as all its children (blue yellow and orange) have to show up. Just like the tree works. It won't show the blue shoes for example if all checkboxes are ticked off(also the parent leather shoes) and i then tick it on and leather shoes becomes indeterminate, nothing will show.

Here's the whole code using JQuery

      $(function () {
      $('input[type="checkbox"]').change(function (e) {
          var checked = $(this).prop("checked"),
              container = $(this).parent(),
              siblings = container.siblings();

          container.find('input[type="checkbox"]').prop({
              indeterminate: false,
              checked: checked
          });

          function checkSiblings(el) {
              var parent = el.parent().parent(),
                  all = true;

              el.siblings().each(function () {
                  return all = ($(this).children('input[type="checkbox"]').prop("checked") === checked);
              });

              if (all && checked) {
                  parent.children('input[type="checkbox"]').prop({
                      indeterminate: false,
                      checked: checked
                  });
                  checkSiblings(parent);
              } else if (all && !checked) {
                  parent.children('input[type="checkbox"]').prop("checked", checked);
                  parent.children('input[type="checkbox"]').prop("indeterminate", (parent.find('input[type="checkbox"]:checked').length > 0));
                  checkSiblings(parent);
              } else {
                  el.parents("li").children('input[type="checkbox"]').prop({
                      indeterminate: true,
                      checked: false
                  });
              }
          }

          checkSiblings(container);

          //Show the corresponding content in the ebook
          if ($('input[type="checkbox"]').prop("checked") == true) {
              var ID = ($(this).attr("id"));
              console.log(ID);
              $("#ebook-" + ID).show("slow");
          }
          if ($('input[type="checkbox"]').prop("checked") == false) {
              var ID = ($(this).attr("id"));
              console.log(ID);
              $("#ebook-" + ID).hide("slow");
          }
      });
  });

Here's a fiddle: http://ift.tt/1JOX1iX




Aucun commentaire:

Enregistrer un commentaire