Examples:


Example 1: Minimal requirements

To launch plugin you just need to put in one parameter, the url of php script which generats a list of words. Format of the list can be either xml or json.


$("#autocomplete1").autocomplete({
	url:'search.php'
});

Example 2: onSelect event

Plugin has four public events. First of them is onSelect, it fires where you pick element from the list. You can activate it by left clicking or pressing 'enter' button on the selected item. In this example I use one second delay before searching, and string must be at least 2 characters. The ansver from server will be in xml format so you can omit type property.


$("#autocomplete2").autocomplete({
	url:'search.php?type=xml',
	minchar:2,
	delay:1000, // in milliseconds
	onSelect:function(){
		alert(this.ac.val())
	},
	type:'xml'
});

Example 3: onKeyPress

onKeyPress event fires when you are typing. It can be used to filtrate user input. In this example you can use only alphabetical characters and white space, all other characters will be deleted. The fillin flag will fill in list before user start typing, because of input string is empty the request to the server will also contains empty mask value (i.e. search.php?type=json&mask=). In this case you will see list of one item with text "The list is empty!". The ansver from server will be in json format and you must set type property to 'json'.


$("#autocomplete3").autocomplete({
	url:'search.php?type=json',
	onKeyPress:function(){
		var o=this;
		setTimeout(function(){
			o.ac.val(o.ac.val().replace(/[^a-z ]+/g,""))
		},50)
	},
	fillin:true,
	type:'json'
});

Example 4: onError event

onError and onSuccess is the last two events, onError fires when AJAX has a problems otherwise onSuccess fires when you get answer from server. For example onError fires where you request for non-existing page. Also its an example of how to disable autocomplete. onSuccess get the same parametrs and scope.


$("#autocomplete4").autocomplete({
	url:'non_exist.php',
	onError:function(XMLHttpRequest, textStatus, errorThrown){
		this.ac.val(textStatus);
		this.ac.attr({disabled:"disabled"}).css({'background-color':'#d0d0d0'});
		this.ul.hide();
		this.img.unbind("click");
	}
});

Example 5: generation list from <select>

All previous examples generats autocomplete from AJAX but you also can do this from html code of current page. You can replace existing select-boxes with autocomplete by using source instead of url. You can pass in plugin either string with selectors like '#select.class' or jQuery object $('#select.class'). Pre-filling and digit-only filtrating is enable.


$("#autocomplete5").autocomplete({
	source:"#select",
		onKeyPress:function(){
		var o=this;
		setTimeout(function(){
			o.ac.val(o.ac.val().replace(/[^0-9]+/g,""))
		},50)
	},
	fillin:true
});

Example 6: generation list from array

If you have no need to use AJAX or have no select-box on your page, you can generate autocomplete from array. For nested arrays [{a:'a'},{b:'b'}] see example 12


$("#autocomplete6").autocomplete({
	source:['a','b','c','d','e'],
	fillin:true
});

Example 7: generation list from object

The same as above. For nested objects like [{a:'a'},{b:'b'}] or {a:{b:c}} see example 12


$("#autocomplete7").autocomplete({
	source:{a:'a',b:'b',c:'c',d:'d',e:'e'},
	fillin:true
});

Example 8: list position

Example of list position at the top of input box


$("#autocomplete8").autocomplete({
	url:'search.php',
	top:true
});

Example 9: real values

Example of real values in non writeable fields


$("#autocomplete9").autocomplete({
	url:'search.php',
	values : true,
	writable : false,
	onSelect:function(){
		alert(this.pairs[this.ac.val()]);
	}
});

Example 10: alternative setup

By onSetup event you can change all properties exept 'width' or change behaviour of elements after autocomplete created. This example demonstrate smooth animation to options list.


$("#autocomplete10").autocomplete({
	onSetup:function(){
		var self = this;
		self.url = 'search.php';
		self.img.unbind("click")
			.bind("click", function() {
				clearTimeout(self.close);
				self.scroll();
				self.ul.slideToggle("slow")
				self.ac.focus();
			});
	}
});

Example 11: progress animation

Example of real usage with event hndling and animation


$("#autocomplete11").autocomplete({
	url:'/content/polygon/search.php?type=json',
	onSuggest:function(){
		this.ac.css({'background-image': 'url("/content/source/progress.gif")'});
	},
	onError:function(XMLHttpRequest, textStatus, errorThrown){
		this.ac.val(textStatus);
		this.ac.attr({disabled:"disabled"}).css({'background-color':'#d0d0d0','background-image':'none'});
		this.ul.hide();
		this.img.unbind("click");
	},
	onDisplay:function(list){
		this.ac.css({'background-image':'none'});
		if (!list)
		this.ul.append("<div style='line-height:100px;text-decoration:underline;text-align:center;'>[Empty list...]</div>");
	},
	minchar:2,
	type:'json'
});

Example 12: custom data format

Example of how to use custom data format


$("#autocomplete12").autocomplete({
    source : [{a:'a'},{b:'b'},{c:'c'},{d:'d'},{e:'e'}],
    fillin : true,
    dataHandler : function(mask){
        var self = this;
        return function(i, n) {
        for (var key in n){
            self.cache[mask].push(n[key]);
        }
        self.store[mask] += self.mark(n[key],mask);
        if(self.values && !self.pairs[n[key]])
            self.pairs[n[key]] = key;
        };
    }
});

Example 13: cascading selectbox

Example of how create selectbox wich depends on another input field


$("#autocomplete13").autocomplete({
    url:function(self){
        var state = $("#c13").attr("checked");
        if (self.ac.data("c13") != state){
            self.ac.data("c13", state);
            self.cache = {};
            self.store = {};
            self.pairs = {};
        }
        return 'search.php?c13='+state;
    },
    partial : true
});

Notice

There is no simple way to re-render autocomplete created from select-box or array (object). You just need to re-create it.


Donation

If you like this plugin please vote for it on jquery site


Thanks to



Advanced options:

Properties

Events

Dependences