DHTMLX Docs & Samples Explorer

Index
dhtmlxtree
Searching and Sorting in Tree

## Searching and Sorting in Tree

### Searching in Tree

#### Enabling Auto Search

First, the meaning of auto search should be explained. When auto selected is switched on, the user can just select any item in the tree and start typing. The tree item, which name is the closes to the typed one, will be selected. Restarting search is done by using the backspace button. Auto search can be enabled only after enabling keyboard navigation:

        <script>
            tree.enableKeyboardNavigation(true);
            tree.enableKeySearch(true); // false to disable
        </script>

This method should be called before any of the data loading methods.

#### Searching Tree

The tree can be searched from script with the help of methods findItem() and findItemIdByLabel(). The methods differ in one thing: whether the searched item will be selected and focused when found or not:

        <script>
            tree.findItem(searchStr, direction, top); // the item will be selected and focused when found
                // or
            tree.findItemIdByLabel(searchStr, direction, top); // the item will not be selected and focused when found
        </script>

The parameters of both these methods are:

- searchStr - the search query;
- direction(false|true) - direction of the search, from the top to the bottom (false), and vice versa (true);
- top(true|false) - start searching from the top (true) or start searching from the currently selected item (false).

### Sorting in Tree

#### Sorting Tree

dhtmlxTree allows its users to sort the tree in ASC or DES orders:

        <script>
            tree.sortTree(itemId, oder, all_levels);
        </script>

The user should indicate the following parameters:

- itemId - id of the node sorting starts from;
- oder(ASC|DES) - sorting order;
- all_levels(true|false) - sorting the tree by all levels (true), or by current level.

#### Custom Defined Sorting

The user can set custom sort function. The function should have two parameters - id_of_item1,id_of_item2. For example:

        <script>
                //define the comparator (in our case it compares the second words in labels)
            function mySortFunc(idA,idB){
                a=(tree.getItemText(idA)).split(" ")[1]||"";
                b=(tree.getItemText(idB)).split(" ")[1]||"";
                return ((a&amp;gt;b)?1:-1);
            }
        </script>

Then setCustomSortFunction() method should be called taking the name of the function as the incoming parameter:

        <script>
                //attach the comparator to the tree
            tree.setCustomSortFunction(mySortFunc);
        </script>

It should be noted that if custom comparator is specified, sortTree() method will use it for sorting.