Introduction
Hi, few days ago my friend asked me if I could help him with Kendo UI component that he needs to create.
Assignment:
- Autocomplete component where you write name of a person, and when you select this person, you will get person's email
- You can also type free type emails, that are not in a list
- Emails are separated by semicolon
Solution
Create autocomplete using Kendo UI is simple. Problem was selecting a value and displaying something else.
In the end we came up with this solution:
<input id="email" type="text" value="" style="width: 100%" />
<script>
var options = {
separator: "; ",
select: addAutocomplete,
filter: "contains",
dataValueField: "email",
dataTextField: "fullName",
dataSource: [
{ email: "xxxx@yyyyy.com", fullName: "John Brown"},
{ email: "peter@yyyyy.com", fullName: "Peter Wright"},
{ email: "l@moore.com", fullName: "Lucas Moore"},
]
};
function addAutocomplete(e) {
e.preventDefault();
var valueFieldName = e.sender.options.dataValueField;
if (valueFieldName) {
var data = e.sender.dataItem(e.item);
var value = e.sender.value();
var separator = e.sender.options.separator;
var index = value.lastIndexOf(separator);
var part = index < 0 ? "" : value.substring(0, index + separator.length);
e.sender.value(part + data[valueFieldName] + separator);
}
}
$("#email").kendoAutoComplete(options);
</script>
First we define all the options for the autocomplete. seperator (semicolon), filter etc... In production you would get dataSource by ajax.
What is different here from normal autocomplete is that we define custom onSelect handler => addAutocomplete.
addAutcomplete explained:
- get the name of dataValueField
- get the index by separator
- set new joined value based on index and dataValueField
Summary
You can find working example here.
Feel free to customize this example to your needs.
Kendo UI is really powerful framework with great components and high flexibility and I can only recommend it.