Select Nodes

Initially

If a node is supposed to be selected initially, set its selected field to true. This is a conventional field name defined by the Default Item Template pattern. If another field specifies whether a node is selected or not, assign its name to the selectedExpr option as shown in the following code.

JavaScript
var hierarchicalData = [{
    name: 'Fruits',
    isSelected: true,
    items: [
        { name: 'Apples' },
        { name: 'Oranges' }
    ]
}, {
    name: 'Vegetables',
    isSelected: true,
    items: [
        { name: 'Cucumbers' },
        { name: 'Tomatoes' }
    ]
}];

$(function() {
    $("#treeViewContainer").dxTreeView({
        dataSource: hierarchicalData,
        keyExpr: 'name',
        displayExpr: 'name',
        selectedExpr: 'isSelected',
        showCheckBoxesMode: 'normal'
    });
});

Using the API

To select or cancel the selection of a node programmatically, call the selectItem(itemElement) or unselectItem(itemElement) method passing the key of the node as a parameter.

JavaScript
$("#treeViewContainer").dxTreeView("selectItem", nodeKey);
// $("#treeViewContainer").dxTreeView("unselectItem", nodeKey);

To select or cancel the selection of all nodes programmatically, call the selectAll() or unselectAll() method.

JavaScript
$("#treeViewContainer").dxTreeView("selectAll");
// $("#treeViewContainer").dxTreeView("unselectAll");
NOTE
If the showCheckBoxesMode is "none", nodes selected using the API do not differ from unselected nodes in appearance.

User Interaction

If only a single node should be in the selected state at a time, set the selectByClick option to true. In this case, an end user can select a node simply by clicking it.

JavaScript
$(function() {
    $("#treeViewContainer").dxTreeView({
        // ...
        selectByClick: true
    });
});

If in your scenario, several nodes could be in the selected state at a time, set the showCheckBoxesMode option to "normal". This setting supplies each node with a check box that selects this node. If in addition, a user should be able to select all nodes at once, set the showCheckBoxesMode option to "selectAll".

JavaScript
$(function() {
    $("#treeViewContainer").dxTreeView({
        // ...
        showCheckBoxesMode: 'normal' // or 'selectAll'
    });
});

Events

When a node changes its selected state, the TreeView fires the itemSelectionChanged event. You can subscribe to it when configuring the widget using the onItemSelectionChanged options, or afterwards using the on() method. For more details, see the Handle Events article.

JavaScript
$(function() {
    $("#treeViewContainer").dxTreeView({
        // ...
        // Subscribing to the event when configuring the widget
        onItemSelectionChanged: function (e) { ... }
    });

    // Subscribing to the event after the widget is configured
    $("#treeViewContainer").dxTreeView("instance").on({
        "itemSelectionChanged": function (e) { ... }
    });
});

View Demo

See Also