Telerik blogs

Normally, when you click a label for a Kendo UI Treeview item, the item toggles between selected and not. But in some scenarios, you just don’t need the item to be selected. Sometimes it makes more sense for the checkboxes to act as the item being selected or not. I’ve had a number of people ask me how to do this recently, so I wanted to share a quick and easy tip on how to make it work.

Add Checkbox, Listen For The Item Select Event

The first thing to do is add checkboxes to the TreeView. This is easy with the checkboxes option. Next, listen for the item selected event. Add a select method to the TreeView options, and call preventDefault() on the events arg to prevent the item from becoming selected.

$("#my-treeview").kendoTreeView({
  dataSource: myDataSource,
  dataTextField: "name",

  // enable checkboxes
  checkboxes: true,

  // listen for item selection
  select: function(e){

    // don't let the item be selected
    e.preventDefault();
  }
});

With a DataSource in place, you’ll have a TreeView that shows checkboxes next to each of the items.

Check / UnCheck The Checkbox

The e argument in the select event gives you several bits of information, including the HTML element that represents the item that was clicked. This element, found in e.node, will contain the checkbox for the item. To find the checkbox, wrap e.node in a jQuery wrapper and the .find(":checkbox") on it.

var checkbox = $(e.node).find(":checkbox");

Since the checkbox variable is a jQuery object, you can run all the usual jQuery methods on it. Grab the “checked” property to find out whether or not it is currently checked, then negate the same property on the checkbox.

var checked = checkbox.prop("checked");
checkbox.prop("checked", !checked);

The Full Code And Result

The final code looks like this:

$("#my-treeview").kendoTreeView({
  dataSource: myDataSource,
  dataTextField: "name",

  // enable checkboxes
  checkboxes: true,

  // listen for item selection and
  // invert the checkbox state
  select: function(e){
    e.preventDefault();

    var checkbox = $(e.node).find(":checkbox");
    var checked = checkbox.prop("checked");
    checkbox.prop("checked", !checked);
  }
});

And when run through a JSFiddle, it looks like this:


About the Author

Derick Bailey

About the Author
Derick Bailey is a Developer Advocate for Kendo UI, a developer, speaker, trainer, screen-caster and much more. He's been slinging code since the late 80’s and doing it professionally since the mid 90's. These days, Derick spends his time primarily writing javascript with back-end languages of all types, including Ruby, NodeJS, .NET and more. Derick blogs atDerickBailey.LosTechies.com, produces screencasts atWatchMeCode.net, tweets as @derickbailey and provides support and assistance for JavaScript, BackboneJS,MarionetteJS and much more around the web.

Comments

Comments are disabled in preview mode.