EasyAutocomplete - guide

JQuery autocomplete plugin.

Include JS and CSS files

First thing you need to do, is to download EasyAutocomplete plugin files. More information about it can be found in the Download section. Javascript and css files(in the actual version) are located in dist folder of the project. If you want to make any changes, uncompiled javascript files and unprocessed sass files can be found in the src folder.

In order to use EasyAutocomplete, add these files in header section of your page.


<!-- JS file -->
<script src="path/to/jquery.easy-autocomplete.min.js"></script> 

<!-- CSS file -->
<link rel="stylesheet" href="path/to/easy-autocomplete.min.css"> 

<!-- Additional CSS Themes file - not required-->
<link rel="stylesheet" href="path/to/easy-autocomplete.themes.min.css"> 


Remember to include jQuery file. You can download library from the jQuery website. Best practice is to use CDN server:

<!-- Using jQuery with a CDN -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>

EasyAutocomplete plugin is very simple to use. Just call function easyAutocomplete on a input field and give it a list of elements to display. That's it.

Example:

HTML:

<input id="basics" />

Javascript:

var options = {
	data: ["blue", "green", "pink", "red", "yellow"]
};

$("#basics").easyAutocomplete(options);

Connect EasyAutocomplete plugin to the external data source. In this example, I have used data file with simple array of colors. File is located on same server("resources/color.json"), so parameter url needs to be resources/colors.json.

Example:

colors.js:

["red", "green", "blue", " black", "yellow"]

HTML:

<input id="provider-file" />

Javascript:

var options = {
	url: "resources/colors.js"
};

$("#provider-file").easyAutocomplete(options);

You can connect EasyAutocomplete plugin to a json data provider. In the example below, plugin loads(via ajax) data from json file, located on the same server. Location of the file needs to be specified in the url parameter. Plugin loads data from the file countries.json, that contains country names and codes. Single elements has format: {"name": "Afghanistan", "code": "AF"}. The last thing you need to do, is to specify parameter getValue, so that the plugin will display correct value on the autocomplete list. It will get value out of the json object.

For better understanding of this example matching is enabled. Countries.json is just a json file with all the countries.

Example:

countries.json:

[ 
  {"name": "Afghanistan", "code": "AF"}, 
  {"name": "Aland Islands", "code": "AX"}, 
  {"name": "Albania", "code": "AL"}, 
  {"name": "Algeria", "code": "DZ"}, 
  {"name": "American Samoa", "code": "AS"}, 
  ...
 ]

HTML:

<input id="provider-json" />

Javascript:

var options = {
	url: "resources/countries.json",

	getValue: "name",

	list: {
		match: {
			enabled: true
		}
	}
};

$("#provider-json").easyAutocomplete(options);


GetValue as function

Parameter getValue doesn't necessary need to be a string. If you are using more complex data, you can declare function that will be used to get value out of the element. For example above you can use:

getValue: function(element) {
	return element.name;
}

EasyAutocomplete plugin can be connected to an xml data provider. It requires more configuration than json, but nothing is overly complex with this jquery autocomplete plugin. As you can see in the example below, plugin loads data from xml file(it doesn't need to be a file, you can use a service, that gives response in xml format). You need to specify, that you will use xml data, so set the parameter to dataType: "xml". Xml file contains names of all the countries. Structure of xml is displayed below. Single element <country> consists of name and iso code. Plugin needs to know where to find elements of the data, so you have to specify node name xmlElementName: "country". Additionaly, you need to write a function that will take value out of the element(see parameter getValue).

Matching is enabled, because countries.xml is just an xml file with all the countries.

Example:

countries.xml:

<?xml version="1.0" encoding="utf-8"?>
<countries>
	<country>
		<name>Afghanistan</name><iso>AF</iso>
	</country>
	<country>
		<name>Aland Islands</name><iso>AX</iso>
	</country>
	<country>
		<name>Albania</name><iso>AL</iso>
	</country>
	<country>
		<name>Algeria</name><iso>DZ</iso>
	</country>
	<country>
		<name>American Samoa</name><iso>AS</iso>
	</country>
  	...
</countries>

HTML:

<input id="provider-xml" />

Javascript:

var options = {
	url: "resources/countries.xml",

	dataType: "xml",
	xmlElementName: "country",

	getValue: function(element) {
		return $(element).find("name").text();
	},

	list: {
		match: {
			enabled: true
		}
	}
};

$("#provider-xml").easyAutocomplete(options);


Complex getValue

Here parameter getValue is a function, that gets name value out of the xml element.

getValue: function(element) {
	return $(element).find("name").text();
}

EasyAutomomplete can take data not only from json / xml files, but can also be connected to an api. The next example uses ajax to get list of countries depending on input phrase. Service generates json response with countries, that matches phrase from field. You can try how it works: country search. In the options used for this example, you can see property url as a function, that takes phrase and sends it to an api. Response from service is converted to the list with suggestions.

Single elements has a format {"name": "Afghanistan", "code": "AF"}, so if you want to show all the countries names, parameter getValue need to take the value "name".

Example:

Remote data:

Example response data for phrase "pol"

HTML:

<input id="provider-remote" />

Javascript:

var options = {
	url: function(phrase) {
		return "api/countrySearch.php?phrase=" + phrase + "&format=json";
	},

	getValue: "name"
};

$("#provider-remote").easyAutocomplete(options);

EasyAutocomplete uses jQuery method ajax for making data requests. Full documentation on this method can be found in the jQuery website. As you can see ajax method has a lot of different settings and can be used in a lot of different ways.

EasyAutocomplete lets you use jquery ajax settings via parameter ajaxSettings. This parameter is used in jquery ajax invoke, simply $.ajax(ajaxSettings), so that gives you many ways to configure this plugin.

For better understanding how this works, check out this duckduckgo autocomplete example.

Easyautocomplete sends requests asynchronously by default(synchronous connections may cause browser to hang). Working with remote services/servers that needs time to generate data always gives some issues. Mainly because you cannot always know how long it will take service to respond.

Easyautocomplete sends request each time input changes its value, so when you type 6 letter word "phrase" there will be 6 requests sended to the service. You cannont know which of the 6 responses will come last, so you don't know if autocomplete list shows suggestions for your word "phrase". It can show suggestions for 5 letter "phras", because you cannot be sure which of the 6 requests come last.

To resolve this issue your service can sent back input phrase and EasyAutocomplete will compare it with the actual input value. To make it work you need to set paramater matchResponseProperty to value where in response is located query value. For the example below I have specified matchResponseProperty: "inputPhrase", because response.json holds query value in parameter "inputPhrase".

This example will show autocomplete list only if you match static response so type "eac".

Example:

response.json:

{
	"items": [
 		"red", "yellow", "brown"
	],
	"inputPhrase": "eac"
}

HTML:

<input id="response-async" />

Javascript:

var options = {
	url: "resources/response.json", 

	listLocation: "items",

	matchResponseProperty: "inputPhrase"
};

$("#response-async").easyAutocomplete(options);


This example uses parameter listLocation, which describes where autocomplete data list is located in json response.

When your response data is more complex, you can specify the location of the list. In the example below, I've used sample google maps json file. List is located under property "markers", so option listLocation should be set to "markers".

Example:

maps.json:

{"markers": [
        {
            "point": "new GLatLng(40.266044,-74.718479)",
            "homeTeam":"Lawrence Library",
            "awayTeam":"LUGip",
            "markerImage":"images/red.png",
            "information": "Linux users group meets second Wednesday of each month.",
            "fixture":"Wednesday 7pm",
            "capacity":"",
            "previousScore":""
        },
        ...
        ]
    }

HTML:

<input id="listLocation" />

Javascript:

var options = {
	url: "resources/maps.json",

	listLocation: "markers",

	getValue: "homeTeam"
};

$("#listLocation").easyAutocomplete(options);

Parameter listLocation can be either string or function.

Select one of the color themes:


Example:

HTML:

<input id="theme" />

Javascript:

var options = {
	
	data: ["Cyclops", "Storm", "Mystique", "Wolverine", "Professor X", "Magneto"],
	
	theme: "dark"
};

$("#theme").easyAutocomplete(options);

You can find more interesting themes in EasyAutocomplete - jquery autocomplete - themes section.


Select theme

Theme can be specified by parameter theme.


Custom css classes

You can also add your own css style classes. Declare them in parametercssClasses.

EasyAutocomplete lets you modify the view of suggestions list. On the EasyAutocomplete - jQuery autocomplete - home page, I have created three examples that use different templates for displaying lists. The first example, "countries", uses simple default list view. The second example, the "countries with flags", uses custom template which, in addition to country name, displays also its flag. The third example, "super heroes", displays heroes names and its miniature head. To do that, example uses build in template called "iconRight".

Templating feature has a couple of build in views for a list:

Template "description" is great to display suggestion value with its description e.g. category. In the example below, next to the vehicle name will be displayed also its type.

To use it, you need to specify type of list template, in this case "description". This tempalte shows two values: one is main value and the second one is the description. So you have to specify how module should find description value in data. In this example, I have used vehicle code, so set parameter fields: {description: "type"}

Example:

HTML:

<input id="template-desc" />

Javascript:

var options = {
	data: [ {name: "Avionet", type: "air", icon: "http://lorempixel.com/100/50/transport/2"},
		{name: "Car", type: "ground", icon: "http://lorempixel.com/100/50/transport/8"},
		{name: "Motorbike", type: "ground", icon: "http://lorempixel.com/100/50/transport/10"},
		{name: "Plane", type: "air", icon: "http://lorempixel.com/100/50/transport/1"},
		{name: "Train", type: "ground", icon: "http://lorempixel.com/100/50/transport/6"}],

	getValue: "name",

	template: {
		type: "description",
		fields: {
			description: "type"
		}
	}
};

$("#template-desc").easyAutocomplete(options);

Template "iconLeft" let you display suggestion value and image located on the left side of the list.

Specify type of list template, in this case "iconLeft". Plugin needs to know how to get access to icon source, so you need to set parameter fields: {iconSrc: "icon"}.

Example:

HTML:

<input id="template-icon-left" />

Javascript:

var options = {
	data: [ {name: "Avionet", type: "air", icon: "http://lorempixel.com/100/50/transport/2"},
		{name: "Car", type: "ground", icon: "http://lorempixel.com/100/50/transport/8"},
		{name: "Motorbike", type: "ground", icon: "http://lorempixel.com/100/50/transport/10"},
		{name: "Plane", type: "air", icon: "http://lorempixel.com/100/50/transport/1"},
		{name: "Train", type: "ground", icon: "http://lorempixel.com/100/50/transport/6"}],

	getValue: "name",

	template: {
		type: "iconLeft",
		fields: {
			iconSrc: "icon"
		}
	}
};

$("#template-icon-left").easyAutocomplete(options);

Template "iconRight" let you display suggestion value and image located on the right side of the list.

Specify type of list template, in this case "iconRight". Plugin needs to know how to get access to icon source, so you need to set parameter fields: {iconSrc: "icon"}.

Example:

HTML:

<input id="template-icon-right" />

Javascript:

var options = {
	data: [ {name: "Avionet", type: "air", icon: "http://lorempixel.com/100/50/transport/2"},
		{name: "Car", type: "ground", icon: "http://lorempixel.com/100/50/transport/8"},
		{name: "Motorbike", type: "ground", icon: "http://lorempixel.com/100/50/transport/10"},
		{name: "Plain", type: "air", icon: "http://lorempixel.com/100/50/transport/1"},
		{name: "Train", type: "ground", icon: "http://lorempixel.com/100/50/transport/6"}],


	getValue: "name",

	template: {
		type: "iconRight",
		fields: {
			iconSrc: "icon"
		}
	}
};

$("#template-icon-right").easyAutocomplete(options);

EasyAutocomplete lets you build your own custom template.

All you need to do is specify template.type to "custom" and define how you want item from list to be displayed. To do that define parameter template.method, it can be either string or function. Your build function must take two arguments: value and item. First value is the value that corresponds to phrase in input, and second item is an element from given list.

Example:

HTML:

<input id="template-custom" />

Javascript:

var options = {
	data: [ {name: "Avionet", type: "air", icon: "http://lorempixel.com/100/50/transport/2"},
		{name: "Car", type: "ground", icon: "http://lorempixel.com/100/50/transport/8"},
		{name: "Motorbike", type: "ground", icon: "http://lorempixel.com/100/50/transport/10"},
		{name: "Plain", type: "air", icon: "http://lorempixel.com/100/50/transport/1"},
		{name: "Train", type: "ground", icon: "http://lorempixel.com/100/50/transport/6"}],


	getValue: "name",

	template: {
		type: "custom",
		method: function(value, item) {
			return "<img src='" + item.icon + "' /> | " + item.type + " | " + value;
		}
	}
};

$("#template-custom").easyAutocomplete(options);

Categories feature is a very useful tool, that lets creating suggestion list consisting of items from couple of different sources.

Section contains information on:

Example belows presents list of suggestions, that contains fruits and vegetables. Categories feature lets showing different data on one autocomplete list. It allows to choose one item from fruits or vegetables.

Example:

fruitsAndVegetables.json:

{
    "fruits": ["Apple", "Cherry", "Clementine", "Honeydew melon", "Watermelon", "Satsuma"],
    "vegetables": ["Pepper", "Jerusalem artichoke", "Green bean", "Fennel", "Courgette", "Yam"]
}

HTML:

<input id="categories-basic" />

Javascript:

var options = {
    url: "resources/fruitsAndVegetables.json",

    categories: [
        {   //Category fruits
            listLocation: "fruits",
            header: "-- Fruits --"
        }, 
        {   //Category vegetables
            listLocation: "vegetables",
            header: "-- Vegetables --"
        }
    ]

};

$("#categories-basic").easyAutocomplete(options);

EasyAutocomplete allows you to invoke function in couple moments. This feature is really helpful when you need to run some code when suggestion list is loaded.

In example below function will be called each time user clicks on one of items on suggestions list.

Example:

HTML:

<input id="trigger-event" />

Javascript:

var options = {
	url: "resources/countries.json",

	getValue: "name",

	list: {
		onClickEvent: function() {
			alert("Click !");
		}	
	}
};

$("#trigger-event").easyAutocomplete(options);

EasyAutocomplete lets you invoke functions in couple of different moments:

Options Description
onSelectItemEvent Invokes function when selected item changes.
onLoadEvent Invokes function when suggestion list loads.
onClickEvent Invokes function when user clicks on one item from suggestion list.
onKeyEnterEvent Invokes function when user types "enter" in input field.
onChooseEvent Invokes function when user types "enter" in input field or clicks one one item from autocomplete list.
onMouseOverEvent Mouse over one of items on suggestion list.
onMouseOutEvent Mouse out from one of items on suggestion list.
onShowListEvent Invokes function whem autocomplete list appears.
onHideListEvent Invokes function whem autocomplete list hides.

Extension EasyAutocomplete has a couple of helpful functions.

Function getSelectedItemIndex returns index of the actual selected item from autocomplete list. Funciton needs to be invoked on jquery object, that represents input text field.

Example below shows how getSelectedItemIndex works.

Example:

HTML:

<input id="function-index" />
<input id="index-holder" />

Javascript:

var options = {
	data: ["Superman", "Wonder Woman", "Iron Man", "Batman", "Catwoman"],
	list: {

		onSelectItemEvent: function() {
			var index = $("#function-index").getSelectedItemIndex();

			$("#index-holder").val(index).trigger("change");
		}
	}
};

$("#function-index").easyAutocomplete(options);

Function getSelectedItemData returns value of selected item. If array of items contains string, function returns string value. If array contains objects, function returns objects. Funciton needs to be invoked on jquery object, that represents input text field.

Example below shows how getSelectedItemData works.

Example:

HTML:

<input id="function-data" />
<input id="data-holder" />

Javascript:

var options = {
	data: [
		{"character": "Cyclops", "realName": "Scott Summers"},
		{"character": "Professor X", "realName": "Charles Francis Xavier"},
		{"character": "Mystique", "realName": "Raven Darkholme"},
		{"character": "Magneto", "realName": "Max Eisenhardt"}
		],

	getValue: "character",

	list: {

		onSelectItemEvent: function() {
			var value = $("#function-data").getSelectedItemData().realName;

			$("#data-holder").val(value).trigger("change");
		}
	}
};

$("#function-data").easyAutocomplete(options);

Function getItemData returns value of item specified by argument index. If array of items contains string, function returns string value. If array contains objects, function returns objects. Funciton needs to be invoked on jquery object, that represents input text field.

EasyAutocomplete plugin allows you to choose, how you want elements list to appear. You can select animation for two actions: show list and hide list. That corresponds to configuration options showAnimation and hideAnimation for show and hide action respectively. You can choose one of three different animation types: fade, slide, normal. Fade animation makes a list appear by changing it's opacity value. Slide animation makes the list slide from above, when show action is runned and slide up, when hide action is runned. Normal type of animation makes list just appear or disappear(no fancy effect).

You can also specify the animation time and declare function that will be runned when the animation will finish(callback).

Example:

HTML:

<input id="animation" />

Javascript:

var options = {
	url: "resources/countries.json",

	getValue: "name",

	list: {
		showAnimation: {
			type: "fade", //normal|slide|fade
			time: 400,
			callback: function() {}
		},

		hideAnimation: {
			type: "slide", //normal|slide|fade
			time: 400,
			callback: function() {}
		}
	}
};

$("#animation").easyAutocomplete(options);

Default animation type is "normal", so no fancy animation.

Feature match is really helpful when you have a long list of elements. You probably want your autocomplete list to show only elements, that match value written in the input field. That's where match comes in handy.

Example:

HTML:

<input id="match" />

Javascript:

var options = {
	data: ["Clark Kent", "Diana Prince", "Tony Stark", "Bruce Wayne", "Selina Kyle"],
	list: {
		match: {
			enabled: true
		}
	}
};

$("#match").easyAutocomplete(options);

Option match is disabled by default.

Sort feature enables you to decide about the order in which elements should appear on the list. You can use basic alphabetical sort or reverse alphabetical sort.

Example:

HTML:

<input id="sort" />

Javascript:

var options = {
	//super heroes
	data: ["Superman", "Wonder Woman", "Iron Man", "Batman", "Catwoman"],
	list: {
		sort: {
			enabled: true
		}
	}
};

$("#sort").easyAutocomplete(options);

Option sort is disabled by default.

You can decide how many elements should appear on the list.

Example:

HTML:

<input id="maxsize" />

Javascript:

var options = {
	//fruits
	data: [
		"apples",
		"apricot",
		"avocado",	
		"bananas",
		"blueberries",
		"cherries",
		"grapefruit",
		"grapes",
		"kiwi fruit",
		"lemons",
		"mangoes",	
		"melons",
		"nectarines",
		"oranges",
		"passion fruit",
		"peaches",	
		"pears",
		"pineapples",
		"plums",
		"rhubarb",
		"rock melon",
		"strawberries",
		"watermelon"
		],
	list: {
		maxNumberOfElements: 10,
		match: {
			enabled: true
		}
	}
};

$("#maxsize").easyAutocomplete(options);

Default value for parameter maxNumberOfElements is 6.

EasyAutocomplete jquery extension lets you delay data request calls. This feature is really helpful, when preparing ajax response data takes alot of resources. It is good to avoid sending multiple request data, when user types couple of letters in text field. Using parameter requestDelay: 500 delays jquery ajax call by 500 miliseconds, so when user types fast the request will be called when user stops typing. Instead of one request for one letter inserted in text field.

Example:

HTML:

<input id="sort" />

Javascript:

var options = {
	url: function(phrase) {
		return "api/countrySearch.php?phrase=" + phrase + "&format=json";
	},

	getValue: "name",
	
	requestDelay: 500
};

$("#request-delay").easyAutocomplete(options);

Option requestDelay is setted up to 0 miliseconds by default(no delay), but it can any number of miliseconds.

Plugin has option to highlight matched phrase on elements list.

In all the previous examples highligthing has been enabled, so phrase has been highlighted on the autocomplete elements list. That's because option highlightPhrase has, by default, the value true. In order to demonstrate change in autocomplete behaviour, in the fallowing example highligthing will be disabled.

Example:

HTML:

<input id="not-highlighted" />

Javascript:

var options = {
	url: "resources/countries.json",

	getValue: function(element) {
		return element.name;
	},

	highlightPhrase: false
};

$("#not-highlighted").easyAutocomplete(options);

Default value for option highlightPhrase is true.

Define input's placeholder.

Example:

HTML:

<input id="placeholder" />

Javascript:

var options = {
	data: ["Superman", "Wonder Woman", "Iron Man", "Batman", "Catwoman"],
	placeholder: "Set up placeholder value"
};

$("#placeholder").easyAutocomplete(options);



You can find more interesting examples in EasyAutocomplete - jquery autocomplete - examples section.