Click here to Skip to main content
15,900,818 members
Articles / Web Development / HTML
Tip/Trick

Treeview Dropdown With Search

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
9 Jan 2015CPOL4 min read 57.1K   2.8K   10   8
This tip implements the TreeView like DropDownList with Search Functionality using Telerik Kendo.

This article appears in the Third Party Products and Tools section. Articles in this section are for the members only and must not be used to promote or advertise products in any way, shape or form. Please report any spam or advertising.

Introduction

This tip implement the Dropdown List (Client Side) with Treeview like items inside server side binding and search within the tree. Now a days, the web is more about how user finds it interactive and easy to use or we can say self descriptive. Most of the time, we need the cascaded search (where one dropdown binds another on the basis of selected value), so either we have multiple dropdowns or the TreeView. Out of these two, Treeview is much user friendly and self descriptive. But having search and fully client side control is what we can call a bonus :). So this tip is all about Treeview Dropdown. Below is the example of what we will implement.

Treeview Dropdown

Background

This is a very basic topic and I will describe this in detail. So a beginner can start with this but having knowledge of JQuery/JavaScript is a must as this is totally based on jquery. Having knowledge of HTML and Kendo is appreciated.

Note: For binding the dropdown with server side, having knowledge of WCF/MVC/WebMethod is a prerequisite.

Using the Code

We will create a webform with client side code only. We will need to include some 'links' and 'Scripts' to the Head part of the page so that we can have required files to run this plugin.

Please include the below files to the Head of HTML.

HTML
<link href="http://cdn.kendostatic.com/2013.2.716/styles/kendo.common.min.css"
rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2013.2.716/styles/kendo.default.min.css"
rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2013.2.716/styles/kendo.dataviz.min.css"
rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2013.2.716/styles/kendo.mobile.all.min.css"
rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2013.2.716/js/kendo.all.min.js"></script>

Above fields are links to resource files from Telerik Kendo. You can get them by clicking on the files or you can manually download the from Telerik itself. 4th script is jquery files.

Now let us move to the Body part of the page.

Place the following HTML to body:

HTML
<form id="form1" runat="server">
   <div>
       <p><label id="lblselected"></label></p>
       <div id="container" style="float: left; min-width: 175px; background-color: #c6c6c6">
           <span>
                 <input type="text" id="treeViewSearchInput" placeholder=" -- select --" />
                 <input id="treeviewDropdownBtn" type="button" value="V" />
           </span>
           <div id="treeview" style="display: none;">
           </div>
       </div>
   </div>
</form>

As you can see, here we use a 'Label' to display the selected value, a 'div' to bind the dropdown items.

To search, we are using an 'input' of type text (it can be of type 'search'). After this, we also used an 'input' of type button to act as Dropdown explorer button.

We have also used little CSS to make it more attractive and dropdown like design. I've used the following CSS.

HTML
<style type="text/css" scoped>
        span.k-in > span.highlight
        {
            background: #7EA700;
            color: #ffffff;
            border: 1px solid green;
            padding: 1px;
        }
    </style>

Now next is the big part that is the JavaScript/JQuery code which is all responsible to make the plugin work. Please go through the code carefully to understand it, although it's self explanatory.

HTML
<script type="text/javascript">
        // Initiate and bind the functions to the HTML controls
        function InitSearch(treeViewId, searchInputId, treeviewDropdownBtn) {
            var <code>tv = $(treeViewId).data('kendoTreeView');

             // Searching functionality with 'keyup' event of the input search box
            $(searchInputId).on('keyup', function () {
                $(treeViewId + ' li.k-item').show();

                $('span.k-in > span.highlight').each(function () {
                    $(this).parent().text($(this).parent().text());
                });

                // ignore if no search term
                if ($.trim($(this).val()) === '') {
                    tv.select() //gets currently selected <li> element
                        .find("span.k-state-selected")
                            .removeClass("k-state-selected"); //removes the highlight class

                    $('#lblselected').html("Selecting: --");
                    return;
                }

                var term = this.value.toUpperCase();
                var tlen = term.length;

                $(treeViewId + ' span.k-in').each(function (index) {
                    var text = $(this).text();
                    var html = '';
                    var q = 0;
                    var p;

                    while ((p = text.toUpperCase().indexOf(term, q)) >= 0) {
                        html += text.substring(q, p) + '<span class="highlight">' + 
                                text.substr(p, tlen) + '</span>';
                        q = p + tlen;
                    }

                    if (q > 0) {
                        html += text.substring(q);
                        $(this).html(html);

                        $(this).parentsUntil('.k-treeview').filter('.k-item').each
                        (function (index, element) {
                            tv.expand($(this));
                            $(this).data('SearchTerm', term);
                        });
                    }
                });

                $(treeViewId + ' li.k-item:not(:has(".highlight"))').hide();
            });

            $(searchInputId).on('blur', function () {
                if ($('#treeViewSearchInput').val() == '')
                {
                    //$('#treeview').hide();             
                } else {
                    $('#treeview').show();
                }
            });

             $(searchInputId).on('focus', function () {
                $('#treeview').show();$('#treeViewSearchInput').keyup();
             });

             $(treeviewDropdownBtn).on('click', function () {
                $('#treeview').toggle();
             });
            

        }

        $(document).ready(function () {
             $.ajax({ type: "GET",
                url: "http://localhost:61808/Service1.svc/GetAllItems",
                async: false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (res) {
                        var $tv = $("#treeview").kendoTreeView({
                        //template: kendo.template($("#treeview-template").html()),
                        dataSource: res,
                        select: onSelect,
                        dragAndDrop: true
                    }).data("kendoTreeView")

                    InitSearch("#treeview", 
                        "#treeViewSearchInput", "#treeviewDropdownBtn");
                },
                error: function (err) {
                    alert(err);
                }
            });
        });

        function onSelect(e) {
            var item = this.dataItem(e.node);
                //alert("Selecting: " + this.text(e.node) + "ID:" + item.id);
                $('#lblselected').html("Selecting: 
                    " + this.text(e.node) + " & ID:" + item.id);
                $('#treeview').hide();
                $('#treeViewSearchInput').val(item.text);
                $('#treeview').hide();
            }

        function setTreeView() {          
            if ($('#treeViewSearchInput').val() == '')
            {
                //$('#treeview').hide();             
            } else {
                $('#treeview').show();
            }
        }
    </script>

In the above code, you can see on document ready, I am binding the Kendo Treeview from remote data. For this, I have created the WFC webservice that returns the Json string data. The data is expected to be like this:

JavaScript
[
  { text: "Item 1" },
  { text: "Item 2", items: [
    { text: "SubItem 2.1" },
    { text: "SubItem 2.2" }
  ] },
  { text: "Item 3" }
]

But if you don't want to create the WCF and want a quick try, you can use this data as below. Just replace the document ready code part with the below one.

JavaScript
$(document).ready(function () {
           var $tv = $("#treeview").kendoTreeView({
               dataSource: { data: [
                   { text: "Item 1" },
                   { text: "Item 2", items: [
                       { text: "SubItem 2.1" },
                       { text: "SubItem 2.2" }
                   ] },
                   { text: "Item 3" }
                   ]},
               select: onSelect,
               dragAndDrop: true
           }).data("kendoTreeView")

           InitSearch("#treeview", "#treeViewSearchInput", "#treeviewDropdownBtn");
       });

Here, I have directly assigned the Json string as Datasource to the treeview.

Now, we are all ready to test our code. Just paste the code in your project on respective position of page and run the project.

Points of Interest

This (Kendo) is one of the most impressive things I ever found for web development as it provides full customization and control to the developer and with little modification, you can create anything and everything you want. Following are the interesting features of this control.

  1. Treeview in Dropdown: This will automatically convert your data to Treeview like structure on the basic of Json string supplied.

    Note: The Json string is all responsible that tells Kendo about Parent and Child of the node. So please observe the Json string carefully.

    Treeview

  2. Searching: From the input box on the top, you can start type and voila!! your data be filtered in the dropdown. Isn't it bolt fast ?.

  3. Highlighted Text: As soon as you type a keyword, you will see the filtration with matching text highlighted.
  4. Selected Item: You can see the selected item to the input box just like the selected item in dropdown.

    treeview Select

Note: In my demo source code, I have created two web pages in which one page is binding the dropdown with local data and the other is using WCF. It also has the WCF webservice file.

So this project is very helpful for you to understand WCF as well.

Thanks

That's all about the Treeview Dropdown with filtering, fully client side controlled. Any comments, suggestions are welcome. Please do leave your feedback and appropriate query. I will reply to you for sure.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
Puneet Goel is an IT Professional with 8+ years. He is specialized in Microsoft Technologies (Asp.NET, SQL Server, Ajax, Jquery, JavaScript, MVC, and Angular). He is an avid member of several development communities and a serial blogger.He loves to learn new technology, do experiments with existing ones, and always happy to help the community.

Comments and Discussions

 
QuestionError Regarding Dropdown Tree Pin
Member 1189207821-Aug-18 1:05
Member 1189207821-Aug-18 1:05 
QuestionMultiSelect Pin
Member 1342332427-Sep-17 5:01
Member 1342332427-Sep-17 5:01 
AnswerRe: MultiSelect Pin
Er. Puneet Goel28-Sep-17 20:11
professionalEr. Puneet Goel28-Sep-17 20:11 
AnswerRe: MultiSelect Pin
Er. Puneet Goel5-Oct-17 23:50
professionalEr. Puneet Goel5-Oct-17 23:50 
QuestionVerbosity Pin
pt140110-Jan-15 0:08
pt140110-Jan-15 0:08 
AnswerRe: Verbosity Pin
BillWoodruff10-Jan-15 6:41
professionalBillWoodruff10-Jan-15 6:41 
GeneralRe: Verbosity Pin
pt140110-Jan-15 22:34
pt140110-Jan-15 22:34 
GeneralRe: Verbosity Pin
Er. Puneet Goel11-Jan-15 17:38
professionalEr. Puneet Goel11-Jan-15 17:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.