---
title: Filter
layout: page
js: examples/filter.js
css: example.css
---

<p id="nav">
    <a href="../13_drag_outside/">&laquo; Example 13</a>
</p>

<h1>Example 14 - filter</h1>

<div>
    <input id="search-term" autofocus></input>
    <button id="search">Search</button>
</div>
<div id="tree1"></div>

<h3>javascript</h3>

{% highlight js %}
const $tree = $("#tree1");

let foundMatch = false;

$tree.tree({
    autoOpen: false,
    data: ExampleData.exampleData,
    useContextMenu: false,
    onCreateLi: (node, $el) => {
        if (foundMatch && !node.openForMatch && !node.parent.matches) {
            $el.addClass("hidden-node");
        }

        if (node.matches) {
            $el.addClass("highlight-node");
        }
    },
});

$("#search").on("click", () => {
    const searchTerm = $("#search-term").val().toLowerCase();

    if (!searchTerm) {
        foundMatch = false;

        tree.iterate((node) => {
            node['openForMatch'] = false;
            node["matches"] = false;
            return true;
        });

        $tree.tree("refresh");
        return;
    }

    const tree = $tree.tree("getTree");
    foundMatch = false;

    tree.iterate((node) => {
        const matches = node.name.toLowerCase().includes(searchTerm);
        node["openForMatch"] = matches;
        node["matches"] = matches;

        if (matches) {
            foundMatch = true;

            if (node.isFolder()) {
                node.is_open = true;
            }

            let parent = node.parent;
            while (parent) {
                parent["openForMatch"] = true;
                parent.is_open = true;
                parent = parent.parent;
            }
        }

        return true;
    });

    $tree.tree("refresh");
});
{% endhighlight %}

<h3>html</h3>

{% highlight html %}
<div>
    <input id="search-term" autofocus></input>
    <button id="search">Search</button>
</div>
<div id="tree1"></div>
{% endhighlight %}

<h3>css</h3>

{% highlight css %}
.hidden-node {
    display: none;
}

.highlight-node > .jqtree-element > .jqtree-title {
    font-weight: bold;
}

#search-term {
    margin-bottom: 16px;
    margin-right: 8px;
}
{% endhighlight %}
