Click here to Skip to main content
15,881,139 members
Articles / Web Development / ASP.NET

Cascading with jQuery AutoComplete

Rate me:
Please Sign up or sign in to vote.
4.61/5 (12 votes)
5 Apr 2012CPOL6 min read 66.1K   2.7K   26   12
cascading functionality with the help of jQuery AutoComplete

In this article I am going to show how to achieve cascading functionality with the help of jQuery AutoComplete UI control rather than we are doing with the help of comobo-box controls till date. By the following screen shot I am going to explain what I am going to achieve in this post and in later on post I am going to explain the part of the code did by me.  

Screen 1: Loading Suggestion  

When user start typing in country textbox  loader image shows that its loading suggestion for the character typed in textbox.

Screen 2: Display Suggestion  

List of suggestion displayed to the end user , which is in turn fetch from the server.  

Screen 3: Display State aftter country selection

Select State textbox get visible once user select country name from the suggestion list.

Screen 4: Display City after State selection

Select city textbox get visible once user select state name from the suggestion list.

Screen 5: Display Search button after selecting city

Search button get visible once user done with the selection of city name from the suggested cities.

Screen 6: Displaying Search data

Search Data get displayed in the gridview control once user click on search button.

Screen 7: "No Data Found" Error Message

Error message get displayed when user types in the textbox and suggestion is not available to display.

Screen 8: "Enter valid Data" Error Message

Alert Message of enter data get displayed when search button is press and one of the textbox value is not present.  

Screen 9: "Enter valid Data" Error Message

Alert Message of enter data get displayed when search button is press and one of the textbox having value for which suggestion is not present. As you can see in the screen shot when I type auto-complete functionality show me the suggestion and once I select suggestion , selected value get placed in the textbox and another row get visible which does the same functionality. Now in the below post I am going to discuss about cascading thing with one textbox only but you can see whole by downloading the full source code of this post.

Aspx page i.e html markup

First start with the Aspx page, what the changes I did for the autocomplete textbox which is going to cascade other autocomplete textbox

ASP.NET
<tr id="trCountry">
  <td>
   <label id="lblCountry" runat="server" text="Select Country" width="150px">   
   </label>
  </td>
  <td>
    <div style="float: left;">
TextBox id="txtCountry" attached class="autosuggest", which tells that when you start typing in its going to display list of suggestion which fetched from the database using ajax and autocomplete plug-in.
ASP.NET
<textbox class="autosuggest" font-size="10px" id="txtCountry" runat="server" 
                  width="250px"></textbox>
<span id="spCountry" style="display:none;color:Red;">No Data Found</span>
Span id="spCountry" It get display when there is no suggestion avaialbe for the character typed in textbox.
<div style="display: none;"

As you see above div having style display=none that means the button and textbox both remains hidden when the page get display on browser.

Button id "btnCountry" on click event get fire when of of the suggestion get selected. So this button fire up the server side event from javascript and make visible the next level textbox. How it fires the event

ASP.NET
<button font-size="10px" id="btnCountry" onclick="btnCountry_Click" 
                runat="server" width="250px"></button>
TextBox id="txtCountryID" this textbox stores the value of the country id which is going to be selected from the suggestion list.
ASP.NET
<textbox id="txtCountryID" runat="server"></textbox>
       </div>
    </div>
  </td>
</tr>

this layout is same for the State and City next level selection textboxes that you can see in full source code. 

jQuery/Javascript

Following is jQuery method that going be utilize for the showing the suggestion , which is provided by autocomplete plug-in.

autocomplete - method

method provided by the pug-in which is in turn get attach with the textbox control which than show the suggestion when user types in. In the above code its attached with the Country textbox, which is same for the State and city textbox that you can see in full code.

var pagePath = window.location.pathname;
         $(function() {

         $("#" + "<%=txtCountry.ClientID %>").autocomplete(
             {

Attribute of autocomplete

source - is from which suggestion will come up, as I am fetching data from the server side page/function I used jQuery ajax function to get the list from server.

Sucess - function attached with this attribute of the ajax function get the data for suggestion list as you can see if the data length is equal to 0 than it display span element which shows that data is not present.

More about ajax function:

Calling Server Side function from Client Side Script

jQuery Ajax Calling functions

source: function(request, response) {

                     $.ajax({
                     url: pagePath + "/GetCountry",
                         data: "{ 'id': '" + request.term + "'}",
                         dataType: "json",
                         type: "POST",
                         contentType: "application/json; charset=utf-8",
                         dataFilter: function(data) { return data; },
                         success: function(data) {
                             if (data.d.length == 0) 
                                 $("#spCountry").show();
                             else
                                 $("#spCountry").hide();
                             response($.map(data.d, function(item) {
                                 {
                                     value = item.Name + " : " + item.ID;
                                     return value;
                                 }
                             }))
                         },
                         error: function(XMLHttpRequest, callStatus, errorThrown) {
                             alert(callStatus);
                         }
                     });
                 },
minLength - no of char typed by use in textbox before the suggestion come up i.e after this many character typed by user than the source get query for suggestion. over here is having value 1 means its start showing suggestion once you start writing in it.
minLength: 1,
select - function associated with this attribute get fire when the use select the item from suggestion list. This is most useful function that do postback and do execute code on serverside by calling serverside button click function , button click function enable State row. As well as this break the string and assign text value to country textbox and id to countryid textbox which is hidden one and which value utilize by the state texbox to display suggestion.
select: function(event, ui) {
                     var str = ui.item.label.split(":");
                     $("#" + "<%=txtCountry.ClientID %>").val(str[0]);
                     $("#" + "<%=txtCountryID.ClientID %>").val(str[1]); 
                     $("#" + "<%=btnCountry.ClientID %>").click();
                 }
             });
         });

Validate function

The function get fire when user click on search button to search people resides in which city once done with selection of country,satate and city.

function Validate() {
      var retVal = true;
      if ($("#spCountry").is(":visible")||
            $("#spSatate").is(":visible") ||
            $("#spCity").is(":visible"))
          retVal = false;
      if($("#" + "").val()=="" ||
         $("#" + "").val()=="" ||
         $("#" + "").val()=="")
          retVal = false;
         if(!retVal) 
      alert("Enter Valid Data"); 
      return retVal;
  }

the code checks for is any of the span element associated with the textbox control is visible which display error message "No Data Found" and also check that is any on textbox contrains blank value. If its all proper it return true value otherwise return false.

CodeBehind Files - aspx.cs file

In cs file I designed class for the testing purpose the name of the class is Common which is going to be utilize by GetCountry, GetState and GetCity methods

public class Common
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int ParentID { get; set; }
}

ID - is the unique value to detect each element uniquely.

Name - is value string value for each element.

ParentID - is value to detect element is child of which element.

People class is used to bind data with the gridview control once user press the search button.

public class People
{
    public string Name { get; set; }
    public string Email { get; set; }
    public int CityID { get; set; }
}

Name- name of the person

Email - email Address

CityID - is the id of city which user belongs.

As I explained before when user start typing in the textbox suggestion list come from the serverside method, following is the one of the method you find other in full code. GetCountry method get called when start typing in Country textbox.

[WebMethod]
    public static List<common> GetCountry(string id)
    {
        try
        {
            List<common><common> country = new List<common> 
            {
                new Common(){ ID=1 ,Name = "India",ParentID=0 },
                new Common(){ ID=2 ,Name = "USA",ParentID=0 },
                new Common(){ ID=3 ,Name = "Ireland",ParentID=0 },
                new Common(){ ID=4 ,Name = "Australia",ParentID=0 }
            };
</common></common>
As I am going to call the method from server side its having attribute WebMethod. In the above code I initialize the collection of country and country is parent element all element have the parentid 0. Method has parameter called id which is contains the value of the textbox which is typed in textbox. ajax calling function in source pass the id as json parameter to method that you can see in above method of jQuery/javascript.
List<common> lstcountry =
                        (from c in country
                         where c.Name.StartsWith(id)
                         select c).ToList<common>();
            return lstcountry;
 
        }
        catch (Exception ex)
        {
            return null;
        }
    }
</common></common>

Above code as you can see apply linq query on the collection and locate the match element which starts by the character typed in textbox.  

Conclusion 

So the above post demonstrate that its easy to achieve the cascading with the help of the auto suggest functionality provided by jQuery autosuggest plug-in.

Note :  Find download code at the start of article and if you have any problem in downloading source code and if you have any query regarding this please mail me at : pranayamr@gmail.com or post comment at below.

License

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


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
QuestionNo Good Coding and waste Pin
Member 1388690426-Jun-18 6:32
Member 1388690426-Jun-18 6:32 
Questionthis is what im looking for Pin
C#Coudou18-Jan-13 16:00
C#Coudou18-Jan-13 16:00 
Questionsuggestion for logic Pin
ashishmaniyar28-Nov-12 17:31
ashishmaniyar28-Nov-12 17:31 
how can i modify this code to fill/reorder elements in combobox as pe user input like say if i type I then comboboc shoud display those elements with I as stating letter say India ,Ierland,Iraq, and then America ???
AnswerRe: suggestion for logic Pin
Pranay Rana29-Nov-12 1:48
professionalPranay Rana29-Nov-12 1:48 
QuestionProblem Pin
Member 82825478-Apr-12 4:33
Member 82825478-Apr-12 4:33 
AnswerRe: Problem Pin
Pranay Rana8-Apr-12 9:03
professionalPranay Rana8-Apr-12 9:03 
GeneralMy vote of 5 Pin
Prasad_Kulkarni5-Apr-12 19:35
Prasad_Kulkarni5-Apr-12 19:35 
GeneralRe: My vote of 5 Pin
Pranay Rana6-Apr-12 9:12
professionalPranay Rana6-Apr-12 9:12 
GeneralMy vote of 4 Pin
HemangDVyas4-Apr-12 7:13
HemangDVyas4-Apr-12 7:13 
GeneralRe: My vote of 4 Pin
Pranay Rana4-Apr-12 7:26
professionalPranay Rana4-Apr-12 7:26 
GeneralMy vote of 5 Pin
Abinash Bishoyi4-Apr-12 2:14
Abinash Bishoyi4-Apr-12 2:14 
GeneralRe: My vote of 5 Pin
Pranay Rana4-Apr-12 4:01
professionalPranay Rana4-Apr-12 4:01 

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

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