Requirement

We need a textbox in which when a user types the name of a country, it automatically shows suggestions as soon as the user starts typing a word. Also with the suggestion, we want the country flag to appear against each country in the suggestion.

Solution

Step 1: Download some sample images of flags of some countries from the internet. I have already downloaded some of the images.

Step 2: Create a table in a database that stores the path of flags along with the country names. Use the following SQL Script to achieve this.
  1. CREATE DATABASE jQueryUIDemo
  2. USE jQueryUIDemo
  3. CREATE TABLE [dbo].[jQueryDemo] (
  4. [Id] INT IDENTITY (1, 1) NOT NULL,
  5. [CountryName] NVARCHAR (50) NOT NULL,
  6. [IconPath] NVARCHAR (MAX) NOT NULL,
  7. PRIMARY KEY CLUSTERED ([Id] ASC)
  8. );
  9. CREATE procedure [dbo].[spGetCountriesDetailsWithIcons]
  10. @term nvarchar(max)
  11. as
  12. begin
  13. select * from jQueryDemo where CountryName like @term + '%'
  14. end
  15. SET IDENTITY_INSERT [dbo].[jQueryDemo] ON
  16. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (1, N'Australia', N'/Icons/australia.gif')
  17. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (2, N'Canada', N'/Icons/canada.gif')
  18. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (3, N'China', N'/Icons/china.gif')
  19. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (4, N'England', N'/Icons/england.gif')
  20. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (5, N'India', N'/Icons/india.gif')
  21. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (6, N'Ireland', N'/Icons/ireland.gif')
  22. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (7, N'Malaysia', N'/Icons/malaysia.gif')
  23. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (8, N'Mexico', N'/Icons/mexico.gif')
  24. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (9, N'Nepal', N'/Icons/nepal.gif')
  25. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (10, N'Pakistan', N'/Icons/pakistan.gif')
  26. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (11, N'Poland', N'/Icons/poland.gif')
  27. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (12, N'Portugal', N'/Icons/portugal.gif')
  28. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (13, N'Russia', N'/Icons/russia.gif')
  29. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (14, N'Spain', N'/Icons/spain.gif')
  30. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (15, N'Sri Lanka', N'/Icons/sri_lanka.gif')
  31. INSERT INTO [dbo].[jQueryDemo] ([Id], [CountryName], [IconPath]) VALUES (16, N'Turkey', N'/Icons/turkey.gif')
  32. SET IDENTITY_INSERT [dbo].[jQueryDemo] OFF
Step 3: Open Visual Studio and create an empty ASP.NET Web application.

Web application

empty tampletes

Step 4: Add a folder named "Icons" and copy all the downloaded images to it. Remember, the name of the folder should be same as that of the path that you have saved in the Database table.

Step 5: Download jQueryUI Autocomplete Widget source files from jQueryUI official website or you can follow the steps to download from my previous article on jQueryUI Autocomplete widget. Copy this downloaded folder to the root directory of the application. We need only the reference of the following files in that downloaded folder.

JQueryUI

Step 6:
Add a class file named "Countries.cs" and replace with the following code.

add new class

class
  1. namespace jQueryUIAutocompleteWithIcons
  2. {
  3. public class Countries
  4. {
  5. public int Id { get; set; }
  6. public string CountryName { get; set; }
  7. public string IconPath { get; set; }
  8. }
  9. }
Step 7: Add the connection strings to connect to the database in the web.config file.
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <configuration>
  3. <system.web>
  4. <compilation debug="true" targetFramework="4.5" />
  5. <httpRuntime targetFramework="4.5" />
  6. </system.web>
  7. <connectionStrings>
  8. <add connectionString="Data Source=.; Database=jQueryUIDemo; Integrated Security=True" name="DBCS" providerName="System.Data.SqlClient"/>
  9. </connectionStrings>
  10. </configuration>
Step 8: Add an ASP.NET Web service file named "CountriesService.asmx" and replaced it with the following code.

add new item

webservice
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Data.SqlClient;
  6. using System.Web.Script.Serialization;
  7. using System.Web.Services;
  8. namespace jQueryUIAutocompleteWithIcons
  9. {
  10. [WebService(Namespace = "http://tempuri.org/")]
  11. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  12. [System.ComponentModel.ToolboxItem(false)]
  13. [System.Web.Script.Services.ScriptService]
  14. public class CountriesService : System.Web.Services.WebService
  15. {
  16. [WebMethod]
  17. public void GetCountriesDetails(string term)
  18. {
  19. string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
  20. List<Countries> countries = new List<Countries>();
  21. using (SqlConnection con = new SqlConnection(CS))
  22. {
  23. SqlCommand cmd = new SqlCommand("spGetCountriesDetailsWithIcons", con);
  24. cmd.CommandType = CommandType.StoredProcedure;
  25. cmd.Parameters.AddWithValue("@term", term);
  26. con.Open();
  27. SqlDataReader dr = cmd.ExecuteReader();
  28. while (dr.Read())
  29. {
  30. Countries country = new Countries();
  31. country.Id = Convert.ToInt32(dr["Id"]);
  32. country.CountryName = dr["CountryName"].ToString();
  33. country.IconPath = dr["IconPath"].ToString();
  34. countries.Add(country);
  35. }
  36. }
  37. JavaScriptSerializer JS = new JavaScriptSerializer();
  38. Context.Response.Write(JS.Serialize(countries));
  39. }
  40. }
  41. }
Press Ctrl + F5 to check that our service is working as expected or not. You will see the following screen.

service

Click the link GetCountriesDetails which is the name of the method that we created in Service code. You will see the following.

GetCountriesDetails

When you enter some characters and press invoke, it will fetch the data from the database using the Stored procedure that we created in SQL.

fetch the data from database

Understanding the code of Web service.

Step 9: Add a new Webform named "Demo.aspx" and add the reference of the following jQuery files to its head section.

jQuery files

Step 10: Add the following code to HTML Source of Demo.aspx page.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs" Inherits="jQueryUIAutocompleteWithIcons.Demo" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <script src="jquery-ui-1.11.4.custom/external/jquery/jquery.js"></script>
  6. <script src="jquery-ui-1.11.4.custom/jquery-ui.js"></script>
  7. <link href="jquery-ui-1.11.4.custom/jquery-ui.css" rel="stylesheet" />
  8. <link href="jquery-ui-1.11.4.custom/jquery-ui.theme.css" rel="stylesheet" />
  9. <link href="jquery-ui-1.11.4.custom/jquery-ui.structure.css" rel="stylesheet" />
  10. <title>jQueryUI Demo</title>
  11. <script type="text/javascript">
  12. $(document).ready(function () {
  13. $("#countryInput").autocomplete({
  14. minLength: 1,
  15. source: function (request, response) {
  16. $.ajax({
  17. url: "CountriesService.asmx/GetCountriesDetails",
  18. method: "post",
  19. data: { term: request.term },
  20. dataType: "json",
  21. success: function (data) {
  22. response(data);
  23. },
  24. error: function (err) {
  25. alert(err);
  26. }
  27. });
  28. },
  29. focus: updateTextbox,
  30. select: updateTextbox
  31. }).autocomplete("instance")._renderItem = function (ul, item) {
  32. return $("<li>")
  33. .append("<img class='imageClass' src=" + item.IconPath + " alt=" + item.CountryName + "/>")
  34. .append('<a>' + item.CountryName + '</a>')
  35. .appendTo(ul);
  36. };
  37. function updateTextbox(event, ui) {
  38. $(this).val(ui.item.CountryName);
  39. return false;
  40. }
  41. });
  42. </script>
  43. <style type="text/css">
  44. .imageClass {
  45. width: 16px;
  46. height: 16px;
  47. padding-right: 4px;
  48. }
  49. </style>
  50. </head>
  51. <body>
  52. <form id="form1" runat="server">
  53. Enter Country Name :
  54. <input type="text" id="countryInput" />
  55. </form>
  56. </body>
  57. </html>
Step 11: Verify that our Solution Explorer should look like the following image. I mean that all the below mentioned files/folder should be available.

Solution Explorer

Step 12: Now press Ctrl + F5 and you will see that our objective is completed.

see that our objective

enter country name

Understanding the HTML and jQuery Code

Code Explanation:

Please read this article on my personal blogs also: debugsolutions and technewsinform. If you liked this article, then please share as much as you can.