Chitika

Thursday, September 13, 2012

How to get jQuery autocomplete id with text

I always here from many of the developers (who are working on jQuery for autocomplete) asking "How to get the value(Id) along with text". So, for all of them i am writing this article.

     In simple manner during autocomplete logic if we type anything in the textbox, ajax call is made and the items are fetched in the form of string to be displayed as suggested results. Now what if, when we want to bring id or value of the record too to our caller page and this is a very common requirement where we need key value pair. In my sample I have a sample page "default.aspx". It contains one search textbox, a hidden textbox for containing the selected item id or value and one input button. User will type anything in textbox and accordingly ajax call will be made to a remote handler for my case  " Handler1.ashx" and records will be fetched. On click the input button the selected id or value will be displayed in the form of alert. Below is the sample code:


<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="http://jquery.bassistance.de/autocomplete/jquery.autocomplete.css"
        rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>    
    <script src="http://jquery.bassistance.de/autocomplete/jquery.autocomplete.js" type="text/javascript">
</script>
//You must refer
 // jQuery file , jQuery.autocomplete.js  & autocomplete.css
</head>
<body>
    <form id="HtmlForm" runat="server">
    <div>
        <asp:TextBox  ID="txtSearch" runat="server"></asp:TextBox>
        <input runat="server" id="hdnValue" type="hidden" />
        <input runat="server" id="btnGetValue" type="button" value="Get Value"/>
    </div>
    </form>
</body>
<script type="text/javascript">
    $("#<%= txtSearch.ClientID %>").autocomplete("~/ Account /Handler1.ashx")
        .result(function (event, data, formatted) {
        if (data) {    
        alert('Value: '+ data[1]);      
            $("#<%= hdnValue.ClientID %>").val(data[1]);
        }       
    });   
</script>
</html>

Next prepare data we want to get it can be from data base or any external source.

For this sample i am using Courses List as


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace AspnetSamples.Account
{
    /// <summary>
    /// Summary description for Handler1
    /// </summary>
    public class Handler1 : IHttpHandler
    {

        public string ProcessRequest(HttpContext context)
        {
            string searchText = string.Empty;
            if (HttpContext.Current.Request.QueryString["q"] != null)
            {
                searchText = HttpContext.Current.Request.QueryString["q"];
            }
            List<Course> courses = new List<Course>();
            for (int i = 1; i < 10; i++)
            {
                Course c = new Course();
                c.Id = 1;
                c.Name = "Asp";
                courses.Add(c);
            }
            //To filter the records based on the given search content
            var filteredCourses = courses.Where(s => s.Name.Contains(searchText.ToUpper()));
            var builder = new StringBuilder();
            foreach (var item in filteredCourses)
            {
                // Remember to use pipe symbol to differciate values,here item value-->text & key-->Id
                builder.Append(string.Format("{0}|{1}|{2}", item.Name, item.Id, Environment.NewLine));
            }
            return builder.ToString();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}



Now run the application any start typing the text when you type for every key press the request will go to handler1.ashx , the it will fetch from the list which is matching for the given text along with the id. You can get the id from the hidden field once you select the text from the auto list otherwise you can't  get the id.
Once you got the value from the hidden field you need to clear the value, otherwise you will get the same value even though you didn't select from auto list. 
Note:
For you information onKeyPress will not work auto complete text box.
Let's sharp you brains of-course we have many solutions take best.





No comments:

Post a Comment