Pages

Auto complete textbox using jQuery

Here I am going to show simplest way to write auto-completer using jQuery ajax. Code has sufficient comments and hence is self explanatory. So I will not explain it any further, simply follow the steps as shown below.

RESULT


ASPX
<form id="form1" runat="server">
<div>
    <asp:TextBox ID="txtInput" runat="server" />
    <asp:Panel ID="pnlSuggestions" runat="server" CssClass="suggestion_box" />
</div>
</form>
Code-behind
/// <summary>
/// Method to be called by jQuery ajax. 
/// Make sure method is static and marked as WebMethod.
/// </summary>
/// <param name="inputText">This is textbox value that will be passed by jQuery ajax request</param>
/// <returns></returns>
[WebMethod]
public static List<string> GetCountries(string inputText)
{
    //Holds sample data
    List<string> countries;
    //Holds matching results
    List<string> matchedCountries;

    //This is for demo purpose. 
    //You can however retrieve data from db in real world applications.
    countries = new List<string>
    {
        "India",
        "Brazil",
        "Australia",
        "Netherlands",
        "United Kingdom",
        "United State of America",
        "Nigeria",
        "Austria",
        "South Africa",
        "Srilanka",
        "Bangladesh",
        "Russia"
    };

    matchedCountries = countries.Where(c => c.StartsWith(inputText, StringComparison.OrdinalIgnoreCase)).ToList();
        
    //Optional
    matchedCountries.Sort();

    return matchedCountries;
}
JavaScript
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    
<script type="text/javascript">
//ID of input textbox control
var INPUT_ID = 'txtInput';
//ID of suggestions panel control
var PANEL_ID = 'pnlSuggestions';
        
//Wait until document has been loaded completely
$(document).ready(function () {
    //Initially hide the panel
    $("#" + PANEL_ID).hide();

    //Attach keyup event handler to input textbox
    $("#" + INPUT_ID).keyup(function () {
        //Get suggestion only if input is valid
        if ($(this).val() != '') {
            loadSuggestions($(this).val());
        }
        else {
            //Hide suggestions panel
            $("#" + PANEL_ID).hide();
        }
    });
});

function loadSuggestions(inputText) {
    $.ajax({
        url: 'Default.aspx/GetCountries',
        type: 'POST',
        data: "{ \"inputText\" : \"" + inputText + "\" }",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: onSuggestionsLoaded,
        error: function () {
            alert('error in request');
        }
    });
}

function onSuggestionsLoaded(data) {
    var list;

    //Create html list element
    list = $('<ul />');

    //Loop through response data and create a list
    $(data.d).each(function (index) {
        list.append(
            $('<li />') //Create list item
                .click(function () {
                    //Select suggestion item
                    $("#" + INPUT_ID).val(data.d[index]);
                    $("#" + PANEL_ID).hide();

                    //Call any function or code block here
                })
                .text(data.d[index])
        );
    });

    //Populate suggestions panel and display
    $("#" + PANEL_ID).html(list);
    $("#" + PANEL_ID).show();
}
</script>
CSS
.suggestion_box ul 
{
    list-style-type: none;
    padding: 0;
    margin: 0;
}

/*Suggestion item css*/
.suggestion_box ul li { }    
.suggestion_box ul li:hover { }
In the above example WebMethod returns list of string values which in jQuery are accessed by using data.d. However if you wish to return custom business objects, you can access returned data objects in jQuery by using data.d[index].propertyName syntax.

For example, in above case, if we had a a class 'Country' with two properties namely Code and Name, WebMethod would return List<Country> and  be accessed in jQuery as data.d[index].Code and data.d[index].Name respectively.

---End---

2 comments: