How to create jQuery Autocomplete Feature Step by Step

How to create jQuery Autocomplete Feature Step by Step

The jQuery Autocomplete feature provides suggestions when you type into the text box. It uses AJAX to fetch these suggestions from the server. The autocomplete feature is very popular and is used by Google Search too. In this tutorial I will teach you how to make this jQuery Autocomplete feature in Step-by-Step manner.

What our jQuery Autocomplete Feature will Do ?

Here I will make a text box and user will type the programming keywords like ‘jQuery’, ‘ASP.NET MVC’, ‘API’, ‘CRUD’ etc. As he goes on typing he will see the suggestions of the tutorial related to his keyword.

He can then select any of the suggestion and then he will be taken to that tutorial’s URL.

jquery autocomplete suggestions

jQuery Autocomplete Code

First of all in your MVC View create a text box and a div:

<div id="viewContent">
    <input type="text" id="searchInput" placeholder="Enter Keywords eg 'jQuery'" />
    <div id="autoCompleteDiv"></div>
</div>

The Autocomplete Suggestions will show on the ‘autoComplete’ div.

Next add the CSS for styling:

<style>
    #viewContent #searchInput, #viewContent #autoCompleteSelect {
        width: 430px;
    }

    #viewContent #searchInput {
        padding: 5px 0;
    }

    #viewContent #autoCompleteSelect option:hover {
        background-color: #d8fff7;
        cursor: pointer;
    }

    ::-webkit-scrollbar {
        width: 10px;
    }

    ::-webkit-scrollbar-track {
        -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
        border-radius: 10px;
    }

    ::-webkit-scrollbar-thumb {
        border-radius: 10px;
        -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
    }
</style>
Creating the jQuery Autocomplete Code

Next coming to the jQuery part, which is the most important as it will create the autocomplete feature.

So first give the reference to jQuery and then add the .keyup() event for the text box. In this event check if the key-code is 40 (when down arrow key is pressed), in that case I do 3 things:

  • Selects the first option of the autocomplete.
  • Sets focus to the autocomplete.
  • Set the text box value as the selected text of autocomplete.

Here ‘autoCompleteSelect’ is an HTML select control that will be dynamically build in the Controller and then it will be returned and shown inside the ‘autoCompleteDiv’ element.

If key-code is not 40 then I do 2 things based on the length of characters typed on the text box.

If the length is greater than 2 then ‘FillAutoComplete()’ function is called else the ‘autoCompleteDiv’ is hidden.

<script>
    $(document).ready(function () {

        $("#searchInput").keyup(function (e) {
            if (e.which == 40) {
                $("#autoCompleteSelect").val($("#autoCompleteSelect option:first").val());
                $("#autoCompleteSelect").focus();
                $(this).val($("#autoCompleteSelect :selected").text());
            }
            else {
                if ($(this).val().length > 2)
                    FillAutoComplete($(this).val());
                else
                    $("#autoCompleteDiv").hide();
            }
        });

    });
</script>

Next I create ‘FillAutoComplete()’ function that will call a C# function on the Controller. It calls that C# function with jQuery AJAX and passes value of the text box to the C# function’s parameter.

//key up event 

function FillAutoComplete(value) {
    $.ajax({
        type: "POST",
        url: "Autocomplete/FillAutoComplete",
        contentType: "application/json; charset=utf-8",
        data: '{"value":"' + value + '"}',
        dataType: "html",
        success: function (result, status, xhr) {
            $("#autoCompleteDiv").html(value);
            $("#autoCompleteDiv").show();
        },
        error: function (xhr, status, error) {
            alert(xhr + " " + status + " " + error);
        }
    });
    return false;
}

On the success callback function the ‘autoCompleteDiv’ is filled with the returned value (which is the Select HTML control) and its display property is set to block (from .show() method).

function ShowAutoName(value) {
    $("#autoCompleteDiv").html(value);
    $("#autoCompleteDiv").show();
}

We also have to add the .change() & .click() events for the ‘autoCompleteSelect’ control. As told earlier it is a

HTML Select control created in the Controller.

The Select HTML controls will look something like this:

<select id="autoCompleteSelect" size="5">
    <option value="http://www.yogihosting.com/using-jquery-to-validate-a-form/">jQuery Validation of Email, Number, Checkbox and More</option>
    <option value="http://www.yogihosting.com/creating-expandable-collapsible-panels-in-jquery/">Creating jQuery Expand Collapse Panels In HTML</option>
    <option value="http://www.yogihosting.com/jquery-ajax-events/">jQuery AJAX Events Complete Guide for Beginners and Experts</option><option value="http://www.yogihosting.com/web-scraper/">How to Create a Web Scraper in ASP.NET MVC and jQuery</option>
</select>

You can clearly see its option’s value contains the URL of the tutorials while the text contains the Title of the tutorials.

On the .change() event the text box value is filled to the selected text of this select control while on the .click() event the user is redirected to the URL (which is set for the value field of the selected option of this select control).

$("#viewContent").on("change", "#autoCompleteSelect", function () {
    $("#searchInput").val($("#autoCompleteSelect :selected").text());
});

$("#viewContent").on("click", "#autoCompleteSelect", function () {
    $("#autoCompleteDiv").hide();
    location.href = $(this).val();
});
Controller Code

In the Controller I create the Autocomplete Select Control. The code for this is:

[HttpPost]
public string FillAutoComplete(string value)
{
    Dictionary<string, string> dataDictionary = new Dictionary<string, string>();
    dataDictionary.Add("jQuery Validation of Email, Number, Checkbox and More", "http://www.yogihosting.com/using-jquery-to-validate-a-form/");
    dataDictionary.Add("jQuery Uncheck Checkbox Tutorial", "http://www.yogihosting.com/check-uncheck-all-checkbox-using-jquery/");
    dataDictionary.Add("Free WordPress Slider Built In jQuery", "http://www.yogihosting.com/wordpress-image-slider-effect-with-meta-slider/");
    dataDictionary.Add("Creating jQuery Expand Collapse Panels In HTML", "http://www.yogihosting.com/creating-expandable-collapsible-panels-in-jquery/");
    dataDictionary.Add("jQuery AJAX Events Complete Guide for Beginners and Experts", "http://www.yogihosting.com/jquery-ajax-events/");
    dataDictionary.Add("How to Create a Web Scraper in ASP.NET MVC and jQuery", "http://www.yogihosting.com/web-scraper/");
    dataDictionary.Add("CRUD Operations in Entity Framework and ASP.NET MVC", "http://www.yogihosting.com/crud-operations-entity-framework/");
    dataDictionary.Add("Implementing TheMovieDB (TMDB) API in ASP.NET MVC", "http://www.yogihosting.com/implement-themoviedb-api/");
    dataDictionary.Add("ASP.NET MVC Data Annotation – Server Side Validation of Controls", "http://www.yogihosting.com/server-side-validation-asp-net-mvc/");
    dataDictionary.Add("How to use CKEditor in ASP.NET MVC", "http://www.yogihosting.com/ckeditor-tutorial-asp-net-mvc/");

    StringBuilder sb = new StringBuilder();
    sb.Append("<select id=\"autoCompleteSelect\" size=\"5\">");

    foreach (KeyValuePair<string, string> entry in dataDictionary)
    {
        if (entry.Key.IndexOf(value, 0, StringComparison.CurrentCultureIgnoreCase) != -1)
            sb.Append("<option value=\"" + entry.Value + "\">" + entry.Key + "</option>");
    }

    sb.Append("</select>");
    return sb.ToString();
}
  • Let us understand the Controller code. This C# function will be called by the jQuery AJAX method on the view.
  • First I fill some values to a dictionary (which you can do from the database). The dictionary key contains the ‘Tutorial Title’ while dictionary value contains the ‘Tutorial URL’.
  • Then I create a ‘select’ control using StringBuilder Class.
  • I check all the dictionary values and adds only those to the ‘select’ control ‘option’ that contains the matching word (entered in the text box).
  • The text box value is send to the value parameter of this C# function.
  • Watch closely that I added the dictionary key to the option text and dictionary value to the option value fields. Finally I return the ‘Select’ control on the last line of this function.

Testing the jQuery Autocomplete functionality

We have successfully created the jQuery Autocomplete feature now let us test it. Open the View on the browser and star adding ‘jQuery’ on the text box. Once 3 letters have been typed you will get the suggestions, select any of the suggestions and you will be taken to the tutorial’s URL.

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.