Click here to Skip to main content
Click here to Skip to main content

Auto Complete with jQuery Template Plugin and AJAX

, 6 Jul 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
AutoComplete Texbox with comma separated insertions

Introduction

Here only one thing that needs introduction is jQuery template Plugin. It gives you more power to render dynamic controls at client side with help of JSON data. It is similar to gridview in asp.net wherein you create layout and assign data source to bind data with Eval/Bind annotations. By using this along with $.ajax I am solving an old problem of auto complete textbox. Remember to add jquery.tmpl.js script file to get benefit of templating.  

Background 

As every developer I too got some R&D kind of task related to auto complete textbox. But this time AjaxToolKit was not more helpful because they want to enter multiple values comma separated with help of auto complete. I googled and finally assembled an idea with multiple techniques. However the task is complete but I found something that is very interesting and quiet powerful call Jquey Template plugin.

Workflow

We will use one empty listbox which is hidden initially along with a textbox. When user starts typing in textbox it send $.ajax request to server to find matching suggestings and get return data in JSON format. We use that JSON to bind existing empty listbox with help of tmpl() plugin and make it visible to enable user to select desired input.

How it Works 

Simple as explain in Introduction. We need to have some container that will hold our data similar to gridview.

<script id="tmplSuggestions" type="text/html">
<option>${Name}</option></script> 

First thing - There is just a weird script with an Id that we use later to bind it and type = 'text/html'. So one thing clear from this line that any thing within this tag will be HTML.

Second thing - There is <option> tag that surely going to part of some <select> control. last thing is ${Name} is equivalent to <%#Eval('ColumnName')%>. Yes this column name of your data source.

Now I have one textbox and a listbox on page as described.

<asp:TextBox runat="server" Width="200px" ID="txtnames" 
  autocomplete="off" onkeyup="getsuggestions(event)"></asp:TextBox>

<asp:ListBox runat="server" Width="200px" CssClass="suggestions" 
  Style="display: none;" ID="lbSuggestion" 
  onclick="Selectsugg('mouse',event)" onkeyup="Selectsugg('key',event)">
</asp:ListBox> 

As user types in textbox it makes a lightweight ajax request to server using.

function getsuggestions(event) {

    $.ajax({
        type: "POST",
        url: "AutoCompleteDemo.aspx/getSuggestions", //pagename.aspx/methodname
        data: "{'keyword':'" + keyword + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg, sd, fg) {
        if (msg.d && msg.d.length > 0) {
        $("#" + '<%=lbSuggestion.ClientID%>').show().children().remove();
        //create option element by using "jquery.tmpl.js" 
        //and add them to listbox
        $("#tmplSuggestions").tmpl(msg.d).appendTo("#" + 
          '<%=lbSuggestion.ClientID%>');
        }
        else {
            $("#" + '<%=lbSuggestion.ClientID%>').hide();
            }
        },
        error: function (gfh, ghg) {
            alert("error");
        },
        complete: function (eret, tytyt) {
            //alert("complete");
        }
    });
}

This method calls some WebMethod in your codebehind as

[WebMethod]
public static object getSuggestions(string keyword)
{
    // Getting data into datatable to depict normal scenario, 
    // This is just illustration you can remove following code with yours
    
    DataTable dtSugg = GetSuggestionsFromDB();
    var list = from dr in dtSugg.AsEnumerable()
               where dr.Field<string>("Name").Contains(keyword)
               select new {Name = dr.Field<string>("Name")};
    return list;
} 

Above function takes some keyword entered in textbox and make a search to data base to find suggestion and return data in form of list that is automatic serialize.

OK Now switch back again to that ajax function this has a Success: attribute that called when data successfully returned from server. Now we will bind that data to our listbox using following code

$("#tmplSuggestions").tmpl(msg.d).appendTo("#" + '<%=lbSuggestion.ClientID%>');

Above line is first find element with id = tmplSuggestions. In our case that is <script> block, then it applies .tmpl() plugin by passing msg.d as data. The result of this is now appended to our listbox 'lbSuggestion' . And you are done.

Note that before adding data to listbox we are clearing its old items by using following line

$("#" + '<%=lbSuggestion.ClientID%>').show().children().remove();

Points to note

Nothing more interesting to show on .aspx page.. but wait there is property called EnableEventValidation= "false". As its name suggests it tells the server to not validate event after postback.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AutoCompleteDemo.aspx.cs"
    Inherits="AutoCompleteTextBox.AutoCompleteDemp"  EnableEventValidation="false" %> 

Why this- As we are modifying DoM on-fly and server is not in sync with such .net controls. So just to get rid of yellow page error.

As Overall exercise it to get suggestion from server and show to client thus code has some hide/show and other keyboard navigation/handling related code. That for sure can be remove if not suits you.

You can use it to render grid.

<script id="tmpGrid" type="text/html">
<tr>  <td>${Name}</td>  <td>${age}</td>  <td>${salary}</td>  <td>${designation}</td> </tr> 
</script>
<table id="tblData"></table>

$("#tmpGrid").tmpl(msg.d).appendTo("#tblData");  

Simple as that for more in depth details I have made a complete article for above client side gridview implementation.   

Conclusion

Interesting thing I/we learn here is jquery.tmpl.js and $.ajax call. please explore it for more fun.

Folks, the world is open to tweak, Hence this code too. Please make it more usable/optimize/relavant as per your requirement.

License

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

Share

About the Author

sumit_kapadia
Software Developer
India India
No Biography provided

Comments and Discussions

 
QuestionGetting id value from the listbox [modified] Pinmembershanthi040715-Jul-13 20:10 
AnswerRe: Getting id value from the listbox Pinmembersumit_kapadia16-Jul-13 6:45 
GeneralRe: Getting id value from the listbox Pinmembershanthi040716-Jul-13 22:58 
QuestionImplications of setting EnableEventValidation="false" Pinprofessionalanand91843-Jul-13 20:16 
AnswerRe: Implications of setting EnableEventValidation="false" Pinmembersumit_kapadia4-Jul-13 2:39 
GeneralRe: Implications of setting EnableEventValidation="false" Pinprofessionalanand91844-Jul-13 2:50 
GeneralMy vote of 5 PinmemberAbinash Bishoyi3-Jul-13 10:42 
GeneralMissing images/downloads PinstaffSmitha Vijayan2-Jul-13 3:40 
GeneralRe: Missing images/downloads Pinmembersumit_kapadia3-Jul-13 5:51 
GeneralRe: Missing images/downloads PinstaffSmitha Vijayan4-Jul-13 6:30 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411022.1 | Last Updated 6 Jul 2013
Article Copyright 2013 by sumit_kapadia
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid