Posted By

lance on 10/27/11


Tagged


Versions (?)

JQuery autocomplete with custom display and fill form


 / Published in: jQuery
 

Only display the name in the search box but get the ID of the record and place it in a hidden field. When select is fired then fill form fields including the hidden field.

  1. $(function () {
  2. $("#<%=hdnSuspectID.ClientID%>").val('0');
  3. $("#<%=txLName.ClientID%>").val('');
  4. $("#<%=txFName.ClientID%>").val('');
  5.  
  6. $("#<%=txLName.ClientID%>").autocomplete({
  7. source: 'Search.ashx',
  8. minLength: 1,
  9. delay: 0,
  10. select: function (event, ui) {
  11. var suspect = ui.item.value.split(' ');
  12. $("#<%=hdnSuspectID.ClientID%>").val(suspect[0]);
  13. $("#<%=txLName.ClientID%>").val(suspect[1]);
  14. $("#<%=txFName.ClientID%>").val(suspect[2]);
  15. return false;
  16. }
  17. })
  18. .data("autocomplete")._renderItem = function (ul, item) {
  19. var suspect = item.value.split(' ');
  20.  
  21. return $("<li></li>")
  22. .data("item.autocomplete", item)
  23. .append("<a>" + suspect[1] + " " + suspect[2] + "</a>")
  24. .appendTo(ul);
  25. };
  26.  
  27. });
  28.  
  29.  
  30. IHttpHandler:
  31. <%@ WebHandler Language="C#" Class="Search" %>
  32.  
  33. using System;
  34. using System.Web;
  35. using System.Data.SqlClient;
  36. using System.Configuration;
  37. using System.Text;
  38. using System.Web.Script.Serialization;
  39. using System.Collections.Generic;
  40.  
  41.  
  42. public class Search : IHttpHandler {
  43.  
  44. public void ProcessRequest(HttpContext context)
  45. {
  46. List<string> names = new List<string>();
  47. context.Response.ContentType = "application/json";
  48. string prefixText = context.Request.QueryString["term"];
  49. using (SqlConnection conn = new SqlConnection())
  50. {
  51. conn.ConnectionString = ConfigurationManager.ConnectionStrings["CMAjax"].ConnectionString;
  52. using (SqlCommand cmd = new SqlCommand())
  53. {
  54. cmd.CommandText = "select top 10 SuspectID, LName, FName from Suspect where LName like @SearchText + '%'";
  55. cmd.Parameters.AddWithValue("@SearchText", prefixText);
  56. cmd.Connection = conn;
  57. conn.Open();
  58. using (SqlDataReader sdr = cmd.ExecuteReader())
  59. {
  60. while (sdr.Read())
  61. {
  62. names.Add(sdr["SuspectID"].ToString() + ' ' + sdr["LName"].ToString() + ' ' + sdr["FName"].ToString());
  63. }
  64. }
  65. conn.Close();
  66. JavaScriptSerializer s = new JavaScriptSerializer();
  67. string json = s.Serialize(names);
  68. context.Response.Write(json);
  69. context.Response.End();
  70. }
  71. }
  72. }
  73.  
  74. public bool IsReusable
  75. {
  76. get
  77. {
  78. return false;
  79. }
  80. }
  81. }

Report this snippet  

You need to login to post a comment.