An example about using JQuery to load list of email addresses got from Generic Hander into the textbox.When user types text in this textbox, it supports auto-complete data due to file jquery.autocomplete.js.Beside that, user can get the selected ID for the selected email address 🙂
Here are the list of email addresses which are used to demonstrate in this demo.
And here is the results of this demo.
How to create autocomplete textbox using JQuery.
1. Design HTML layout as above image
<form id="form1" runat="server"> <div> Email Address : <asp:TextBox ID="txtEmailAddress" runat="server" Width="200"> </asp:TextBox> <asp:RequiredFieldValidator ID="ReqEmail" SetFocusOnError="true" ControlToValidate="txtEmailAddress" ErrorMessage="Please input email address!" runat="server" Display="Dynamic" /> <input runat="server" id="hidEmailID" type="hidden" value="" /> <asp:Button runat="server" id="btnGetEmailAddressID" Text ="Get Email Address ID" onclick="btnGetValue_Click"></asp:Button> </div> </form> |
2. Include file jquery-1.2.6.js, jquery.autocomplete.js into project and declare to use them in Default.aspx
<script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script> <script src="Scripts/jquery.autocomplete.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="CSS/jquery.autocomplete.css"/> |
3. JQuery to load data to textbox in page Default.aspx
This script request to Generic Handler named LoadEmailAddress.ashx to get data and load into txtEmailAddress
<script type="text/javascript"> $(document).ready(function() { $("#<%= txtEmailAddress.ClientID %>").autocomplete('LoadEmailAddress.ashx'). result(function (event, data, formatted) { // data[0] : Email Address, data[1] : Email ID // Set Selected email ID to hidden field $("#<%= hidEmailID.ClientID %>").val(data[1]); }); }); </script> |
4. Create Generic Handler file named “LoadEmailAddress.ashx”
This class includes a method called “ProcessRequest” that is responsible for writing list of email addresses to the HttpContext.Response.Output stream.
To understand more ASHX file, refer this link : ASHX
We aslo can create method to get data from database instead of creating data by hard code.
public void ProcessRequest (HttpContext context) { Dictionary<int, string> lstEmails = new Dictionary<int, string>(); lstEmails.Add(1, "[email protected]"); lstEmails.Add(2, "[email protected]"); lstEmails.Add(3, "[email protected]"); lstEmails.Add(4, "[email protected]"); lstEmails.Add(5, "[email protected]"); lstEmails.Add(6, "[email protected]"); lstEmails.Add(7, "[email protected]"); lstEmails.Add(8, "[email protected]"); lstEmails.Add(9, "[email protected]"); lstEmails.Add(10, "[email protected]"); StringBuilder builder = new StringBuilder(); foreach (KeyValuePair<int, string> item in lstEmails) { builder.Append(string.Format("{0}|{1}|{2}", item.Value, item.Key, Environment.NewLine)); } context.Response.Write(builder.ToString()); } |