title: Recursive Checkbox Selection in Treeview | Telerik MVC
body: <p>I recently encountered an issue dealing with the <a href="http://www.telerik.com/community/forums/aspnet-mvc/treeview.aspx" rel="nofollow">Telerik Treeview component</a> and handling recursive selection with checkboxes when handling larger data sets (500-1000+ nodes).</p>
  
  <p>With smaller data sets (100-300 nodes) the Treeview and its selection methods work as follows (as they should):</p>
  
  <ul>
  <li><p><strong>Initially - all nodes are selected.</strong></p></li>
  <li><p><strong>Clicking a parent node toggles selection of all of the child nodes.</strong></p></li>
  <li><strong>Unselecting a single child node will unselect the parent (and any grandparent / top-level nodes)</strong></li>
  </ul>
  
  <p>Most of these things I believe are fairly commonplace when dealing with Treeviews and selection. The current method that is being used isn't the cleanest and calls an unnecessary amount of additional events to be fired during the selection process.</p>
  
  <p>I was just curious if anyone had handled an issue similar to this before I began tearing apart the current code (available below).</p>
  
  <p><strong>Existing Selection Code:</strong></p>
  
  <pre><code>$('#TreeView').find("li").find('&gt; div &gt; .t-checkbox :checkbox').bind('click', function (e) {
  
          var isChecked = $(e.target).is(':checked');
          var treeView = $($(e.target).closest('.t-treeview')).data('tTreeView');
          var item = $(e.target).closest('.t-item');
          var checkboxes = item.find('.t-checkbox :checkbox');
          $.each(checkboxes, function (index, checkbox) { $(checkbox).attr('checked', isChecked ? true : false); treeView.checkboxClick(e, checkbox); });
          var siblings = item.parent().find('&gt; li .t-checkbox');
          var siblingsLength = siblings.length;
          var checkedLength = siblings.find(':checked').length;
          if (siblingsLength == checkedLength) {
              var parentCheckBox = item.parent().closest('.t-item').find('&gt; div .t-checkbox :checkbox');
              var grandparentCheckBox = item.parent().parent().parent().closest('.t-item').find('&gt; div .t-checkbox :checkbox');
              parentCheckBox.attr('checked', true)
              grandparentCheckBox.attr('checked', true)
              treeView.checkboxClick(e, parentCheckBox)
              treeView.checkboxClick(e, grandparentCheckBox)
          }
          else {
              var parentCheckBox = item.parent().closest('.t-item').find('&gt; div .t-checkbox :checkbox');
              var grandparentCheckBox = item.parent().parent().parent().closest('.t-item').find('&gt; div .t-checkbox :checkbox');
              parentCheckBox.attr('checked', false)
              grandparentCheckBox.attr('checked', false)
              treeView.checkboxClick(e, parentCheckBox)
              treeView.checkboxClick(e, grandparentCheckBox)
          }
      });
  </code></pre>