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.
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.
<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
:
<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.
<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.
<script type="text/javascript">
function InitSearch(treeViewId, searchInputId, treeviewDropdownBtn) {
var <code>tv = $(treeViewId).data('kendoTreeView');
$(searchInputId).on('keyup', function () {
$(treeViewId + ' li.k-item').show();
$('span.k-in > span.highlight').each(function () {
$(this).parent().text($(this).parent().text());
});
if ($.trim($(this).val()) === '') {
tv.select()
.find("span.k-state-selected")
.removeClass("k-state-selected");
$('#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() == '')
{
} 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({
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);
$('#lblselected').html("Selecting:
" + this.text(e.node) + " & ID:" + item.id);
$('#treeview').hide();
$('#treeViewSearchInput').val(item.text);
$('#treeview').hide();
}
function setTreeView() {
if ($('#treeViewSearchInput').val() == '')
{
} 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:
[
{ 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.
$(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.
- 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.
- 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 ?.
- Highlighted Text: As soon as you type a keyword, you will see the filtration with matching text highlighted.
- Selected Item: You can see the selected item to the input box just like the selected item in dropdown.
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.