Autocomplete
Prehistory
First of all, I want to say, that this plugin was developed for KyivStar, therefore all fine details were studied and stipulated very carefully. For example, what should occur, when the user would reach last element of the list: whether it should rest against the end or begin a cycle all over again. Or whether the list should disappear when the cursor is out of it. All this passed through business analysts’ and designer and only then came to me.
On the other hand I tried to make autocomplete multifunctional (multipurpose) and as simple as possible for any person to use it on ones site. Remarkable is that even with switched off javascript the site would not lose functionality, and visitor can enter data anyway. Autocomplete was not made as a filtrator of data entered by the user but the tool which helps the user to fill the form more quickly.
Well-known plugin jquery.suggest was taken as an example. Pieces of which can be identified in some methods. In spite of the fact that I took mechanism, I have added some new functions and have removed some errors. So in last version jquery.suggest the code became more readable thanks to the removal of one check. But at the end of the list the cursor (illumination) disappears for one position and then again appears at the first element of the list. It happens because jquery (in traversing) always return itself to the object and doesn’t give value to quantity chosen nodes. Another authors fault that he persistently tries to apply $.fn.bgiframe to the list <ul/>, This invention is certainly noble, but I couldn’t deal with this on practice.
Functions that were added: generation of the list from select-box, the limited visible part of the list with scrolling and prefilling of the list for it to look like a select-box. One more events handling onKeyPress. Well-known algorithm of caching MRU was deleted and replaced with my cache algorithm, this takes a lot of memory but it very fast!
Downloads
Last update 14.09.2009!
HTML file with examples (autocomplete.html)
Plugin itself (jquery.autocomplete.js)
Styles (autocomplete.css)
Little blue arrow (select.gif)
Progress bar backgraund image (progress.gif)
Php backend (search.phps)
Copy all this files to your own local web-server in root directory, rename search.phps to search.php and run http://path.to.your.server/autocomplete.html.
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. Sorry but nested arrays are not supported so you can not use [{a:'a'},{b:'b'}]
$("#autocomplete6").autocomplete({
source:['a','b','c','d','e'],
fillin:true
});
Example 7: generation list from object
The same as above. Sorry but nested objects are not supported so you can not use [{a:'a'},{b:'b'}] or {a:{b:c}}
$("#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/autocomplete/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;
}
});
Example 14: autocomplete form selectbox
Example of how to customize selectbox with plug-in
$("select#autocomplete14").autocomplete();
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
- Damir
- Connected
- Joey
- Pasha
- Morleydots
- Gianfrasoft
- Andrea
- Ztalker
- WooYek
- Naden
- Andrea Riciputi
Advanced options
Properties
- url - [String|Function] ajax url
- source - [String|jQuery|Array|Object] css selector or raw html, jQuery object, array [], object {}
- minchar - [Integer] The minimum number of characters a user has to type before the autocompleter activates (default 1)
- delay - [Integer] The delay in milliseconds the autocompleter waits after a keystroke to activate itself (default 50 miliseconds)
- fillin - [Boolean] Pre-fill in (default false)
- width - [Integer] width of autocomplete (default 200)
- type - [String] type of server responce xml or json (default xml)
- top - [Boolean] position of the list (default false to the bottom)
- writable - [Boolean] allows to user write his own option (default true)
- values - [Boolean] keep values for options (default false)
- partial - [Boolean] makes request to server after each new letter (default false)
Events
- onKeyPress - fires when user press a button
- onSetup - fires once when autocomplit created
- onSuggest - fires after onKeyPress but before ajax request send
- onSuccess - fires when AJAX retuns result
- onError - fires when AJAX retuns error
- onDisplay - fires before list of items shows
- onSelect - fires when user picks up from list
Dependences
- jQuery - requires jQuery 1.2.6 or higher
- bgiframe - use bgiframe if installed
Свежие комментарии