Live Demo
Start typing a programming language name below to see live filtered suggestions from a local array of ~10 terms.
No selection yet.
jQuery UI's autocomplete() widget adds type-ahead suggestions to a text input. As the user types, a dropdown of matching options appears below the field — the list can come from a plain local array or be fetched dynamically from a server.
| Option / Event | Description | Example |
|---|---|---|
.autocomplete() | Attaches suggestion behavior to a text input. | $('#t').autocomplete({ source: arr }); |
source (array) | A local JS array of possible values. | source: ['JavaScript', 'PHP', 'Python'] |
minLength | Minimum characters typed before suggestions appear. | minLength: 2 |
source (function) | A function that filters/returns matches, e.g. from a remote endpoint. | source: function(req, res){ ... } |
select | Fires when the user picks a suggestion. | select: function(e, ui){ ui.item.value } |
source for small, fixed lists (countries, tags). Switch to a function source once the list is large or lives on the server, so you only fetch matches for what the user actually typed.
var languages = ['JavaScript', 'PHP', 'Python', 'Java', 'C++'];
$('#lang').autocomplete({
source: languages
});
minLength Option
$('#lang').autocomplete({
source: languages,
minLength: 2 // wait for at least 2 characters
});
source (Function)
// simulates a server call with setTimeout; swap for $.ajax in real apps
$('#lang').autocomplete({
source: function(request, response){
setTimeout(function(){
var term = request.term.toLowerCase();
var matches = $.grep(languages, function(item){
return item.toLowerCase().indexOf(term) !== -1;
});
response(matches);
}, 250); // artificial network delay
}
});
select Event
$('#lang').autocomplete({
source: languages,
select: function(e, ui){
console.log('Chosen: ' + ui.item.value);
}
});
Start typing a programming language name below to see live filtered suggestions from a local array of ~10 terms.