jQuery Autocomplete enables users to quickly find and select from a pre-populated list of values as they type, leverage, search and filter. Autocomplete can be done with both client side data and server side. Client side means we fetch data only once then the filter will be applied on that data. Server side means as and when user types it goes to server and fetches relevant data.
Client Side Autocomplete:
Javascript:
- $(document).ready(function()
- {
-
- var availableKeywords = [
- "ActionScript",
- "BASIC",
- "C",
- "C++",
- "Erlang",
- "Fortran",
- "Groovy",
- "Haskell",
- "Java",
- "JavaScript",
- "Python",
- "Ruby",
- "Scala",
- "Scheme"];
-
-
- $("#keywords").autocomplete({
- source: availableKeywords
- });
-
- });
Html:
- <div class="ui-widget">
- <label for="keywords">Keywords: </label>
- <input id="keywords">
- </div>
The above example is based on client side data. Here the data is at client side in the form of an array, but many times we may need data from the server dynamically. So here I will explain how to do that. When we deal with server side, we should first define a url which serves the request from the client. Server should return data in JSON format.
Autocomplete with Remote Data:
Javascript:
- $("#cities").autocomplete({
-
- source: "search.php",
-
- minLength: 2,
-
- select: function(event, ui)
- {
-
-
-
- }
-
- });
Html:
- <div class="ui-widget">
- <label for="cities">Cities: </label>
- <input id="cities">
- </div>
Note: jQuery autocomplete requires jquery-ui.js external javascript file.