jQuery UI TextBox AutoComplete with Remote Data Source (Back to Basics)
Posted by: Suprotim Agarwal ,
on 5/10/2015,
in
Category jQuery and ASP.NET
Abstract: Using jQuery and jQuery UI, we will first bind a textbox autocomplete widget to a remote datasource.
The jQuery Autocomplete widget was reintroduced in jQuery UI 1.8. It is a simple widget attached to a text input field and can be connected to a range of data sources. It provides suggestions in a dropdown menu as the user begins typing in the textbox. In a previous article Getting started with jQuery and jQuery UI – Back to Basics, we briefly introduced the jQuery UI AutoComplete widget. If you have never used any of the jQuery UI controls, then before proceeding further, I recommend you to click here to understand how to setup jQuery UI.
In this recipe, we will start by using a simply array as a datasource for the autocomplete widget; and then in the subsequent example, we will use a remote datasource.
Create a new HTML file called ‘Autocomplete.html’ and declare a textbox in your <body> element:
<input id="myText" />
To enable this as an autocomplete textbox, write the following code:
$(function () {
var dataSrc = ["australia", "austria", "antartica", "argentina", "algeria"];
$("#myText").autocomplete({
source:dataSrc
});
});
Here we have implemented a basic autocomplete with a local array as its data source. The source option is mandatory to which we are specifying a local array of strings.
Save and run this file in the browser and as you start typing the first alphabet, it is matched against a list of the countries defined in our array and the matches get displayed in a drop-down menu attached to the <input>.
Note: If you are using the jquery-ui.min.css file in your projects, you may encounter a message that says “5 results are available, use up and down arrow keys to navigate”. This behavior occurs especially when you are using jQuery UI 1.9 onwards. The jQuery UI team has added ARIA live regions to announce when results become available and how to navigate through the list of suggestions. This is helpful for screen readers. You can easily turn it off by adding this line of code after your reference to the css file .ui-helper-hidden-accessible { position: absolute; left: -9999px; }
Live Demo: http://www.jquerycookbook.com/demos/S2-InputControls/16-Autocomplete.html
jQuery TextBox Autocomplete with Remote Data Source
Our previous example was a simple one where we used an array defined locally. To use the Autocomplete widget to the best of its capability, we should bind it to an external data source.
We will be using the remote API http://www.geobytes.com/free-ajax-cities-jsonp-api.htm which is free to use (upto <50K requests per day), supports JSON-P and does not require an API key to work (as of this writing).
Note: This service is up and running at the time of this writing, but I cannot guarantee its uptime or existence. In case, this service goes offline, simply replace the API with another one of your choice that supports JSON-P.
Note 2: You can run this example without a web server. However because of how AJAX works, you cannot run any of the AJAX examples (especially in Chrome browser) without using a web server like IIS.
If you are new to JSON-P, please refer to JSON and JSONP in jQuery - Back to Basics before proceeding.
Create a new HTML file called ‘Autocomplete-ajax.html’ and add the following HTML:
<body>
<input id="myText" />
</body>
Use the following code to bind the Autocomplete widget to the Geobytes API:
$(function () {
var getData = function (request, response) {
$.getJSON(
"http://gd.geobytes.com/AutoCompleteCity?callback=?&q=" + request.term,
function (data) {
response(data);
});
};
var selectItem = function (event, ui) {
$("#myText").val(ui.item.value);
return false;
}
$("#myText").autocomplete({
source: getData,
select: selectItem,
minLength: 4,
change: function() {
$("#myText").val("").css("display", 2);
}
});
});
Here we are using the getData() function as the value of our AutoComplete source option. This function is called every time the user enters text in the <input> field. We first make a JSONP request to the Geobytes API containing the data. The data returned is passed to the response callback function, which is passed to the source function as the second argument.
As already explained in a previous article Getting started with jQuery $.ajax() – Back to Basics, you can’t send an XMLHTTP request to a different domain. The workaround is to use JSONP where we use &jsoncallback=? In the url to notify the external website that we want to receive JSONP data. Internally jQuery’s $.getJSON() function treats this request as if the web browser was requesting an external JavaScript file and thus makes the call successful.
We then define the selectItem handler for the autocomplete's select event. This function is automatically passed two arguments, which are the event object and a ui object containing the suggestion that was selected.
The getData and selectItem are then passed to the Autocomplete source option and select event respectively. We are also setting the minLength option which specifies the minimum number of characters a user must type before a search is performed. If your data source is large, a single character search could match a few thousand items. In such cases, it is best to specify minLength to a higher value like 3 or 4.
Save and view the file in your browser. In the textbox, type minimum of 4 characters and the autocomplete will display some suggestions.
Live Demo: http://www.jquerycookbook.com/demos/S2-InputControls/16.1-Autocomplete-ajax.html
If you liked this article, take a look at my new book The Absolutely Awesome jQuery Cookbook which contains scores of practical jQuery/jQueryUI recipes you can use in your projects right away.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of
DotNetCurry,
DNC Magazine for Developers,
SQLServerCurry and
DevCurry. He has also authored a couple of books
51 Recipes using jQuery with ASP.NET Controls and
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn