Click here to Skip to main content
15,908,173 members
Articles / Programming Languages / Javascript
Tip/Trick

Outlook like autocomplete in Kendo UI

Rate me:
Please Sign up or sign in to vote.
1.00/5 (2 votes)
24 May 2016CPOL 6.6K   1  
Outlook like autocomplete using Kendo UI with online demo.

Introduction

Hi, few days ago my friend asked me if I could help him with Kendo UI component that he needs to create.

Assignment:

  1. Autocomplete component where you write name of a person, and when you select this person, you will get person's email
  2. You can also type free type emails, that are not in a list
  3. 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:

JavaScript
<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:

  1.  get the name of dataValueField
  2.  get the index by separator
  3. 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.

License

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


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --