How to create jQuery Autocomplete Feature in Step by Step manner

How to create jQuery Autocomplete Feature in Step by Step manner

The jQuery Autocomplete feature provides suggestions when you type on a text box. It uses AJAX to fetch these suggestions from the server. The autocomplete feature is very popular and is used by Google Search to. 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 the user goes on typing he will see the suggestions of the tutorial related to his keyword.

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

jquery autocomplete suggestions

jQuery Autocomplete Code

First of all in your ASP.NET MVC View, create a text box and a div tags:

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

Note: The Autocomplete Suggestions will show on the autoComplete div.

Next add the CSS for styling purpose:

<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.

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 do 3 things:

  • Selects the first item of the autocomplete.
  • Set the focus to the autocomplete.
  • Set the text box value same as the selected text of autocomplete.

Here autoCompleteSelect is an HTML select control that will be dynamically build by the Controller. It will be shown inside the autoCompleteDiv element.

If key-code is not 40 then I do 2 things which are 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 an Action method of the Controller.

It calls the Action method with jQuery AJAX Method and passes value of the text box to the Action method’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 it’s display property is set to block (using the .show() method).

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

I 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, and will look something like this:

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

You can clearly see it’s 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 to 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’s Action Code

In the Controller’s Action method 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", "https://www.yogihosting.com/using-jquery-to-validate-a-form/");
    dataDictionary.Add("jQuery Uncheck Checkbox Tutorial", "https://www.yogihosting.com/check-uncheck-all-checkbox-using-jquery/");
    dataDictionary.Add("Free WordPress Slider Built In jQuery", "https://www.yogihosting.com/wordpress-image-slider-effect-with-meta-slider/");
    dataDictionary.Add("Creating jQuery Expand Collapse Panels In HTML", "https://www.yogihosting.com/creating-expandable-collapsible-panels-in-jquery/");
    dataDictionary.Add("jQuery AJAX Events Complete Guide for Beginners and Experts", "https://www.yogihosting.com/jquery-ajax-events/");
    dataDictionary.Add("How to Create a Web Scraper in ASP.NET MVC and jQuery", "https://www.yogihosting.com/web-scraper/");
    dataDictionary.Add("CRUD Operations in Entity Framework and ASP.NET MVC", "https://www.yogihosting.com/crud-operations-entity-framework/");
    dataDictionary.Add("Implementing TheMovieDB (TMDB) API in ASP.NET MVC", "https://www.yogihosting.com/implement-themoviedb-api/");
    dataDictionary.Add("ASP.NET MVC Data Annotation – Server Side Validation of Controls", "https://www.yogihosting.com/server-side-validation-asp-net-mvc/");
    dataDictionary.Add("How to use CKEditor in ASP.NET MVC", "https://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 change). The dictionary key contains the Tutorial’s Title while dictionary value contains the Tutorial’s URL.
  • Then I create a select control using the StringBuilder object.
  • I check all the dictionary values and adds only those to the select control’s option that contains the matching word entered on the text box.
  • The text box value is send to the parameter of the Action method.
  • 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 the code.
I strongly recommend you to know how to Consume an ASP.NET Web API in jQuery from Start. The tutorial also contains the Codes to download.

Testing the jQuery Autocomplete functionality

I successfully created the jQuery Autocomplete feature. Now it’s time to 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 corresponding tutorial’s URL.

DOWNLOAD the source codes:

DOWNLOAD

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate