--- title: Auto-complete layout: nested-component.html github: components/forms/auto-complete.html ---
Auto-complete components are ajax powered search fields. The input returns a list of results filtered based on the query, highlighting the query in each result.
NOTE: This plugin CAN ONLY be configured and initialized through javascript.
The minimum required configuration for the auto-complete component takes two functions:
serviceUrl
and transformResult
which both needs to return a value detailed below.
The serviceUrl function must return a full url including query and any optional parameters.
The function provides the query as an argument.
Example:
serviceUrl: function(query) {
return 'https://api.usa.gov/jobs/search.json?query=' + query;
},
The transformResult function must return an object:
{query: 'the_query_to_highlight', value: 'the_value_to_show', data: null}
The function provides the Ajax response and the query as arguments.
The data property is optional but can be used to group results together with the groupBy option.
Example:
transformResult: function(response, query) {
return {
query: query,
suggestions: $.map(response, function(item) {
return {value: item.position_title, data: {location: item.locations[0]}};
})
};
}
Now it's just a matter of wrapping a <input type="text"/>
in a <div>
wich must have the auto-complete
class and initializing the plugin:
$('.auto-complete').autoCompleteWrapper({
serviceUrl: ...,
transformResult: ...
});
Search suggestions for the demos below: nurse, mechanic, pilot, cook
Loading...
var autoCompleteEndpoint = 'https://api.usa.gov/jobs';
$('.auto-complete').autoCompleteWrapper({
serviceUrl: function(query) {
return autoCompleteEndpoint + '/' + 'search.json?query=' + query;
},
transformResult: function(response, query) {
response = JSON.parse(response);
return {
query: query,
suggestions: $.map(response, function(item) {
return {value: item.position_title, data: {location: item.locations[0]}};
})
}
},
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
},
deferRequestBy: 500,
groupBy: 'location'
});
NYI
Invert the colors of the auto-complete results by adding a auto-complete--inverse
modifier class to the <div class="auto-complete">
Loading...
var autoCompleteEndpoint = 'https://api.usa.gov/jobs';
$('.auto-complete').autoCompleteWrapper({
serviceUrl: function(query) {
return autoCompleteEndpoint + '/' + 'search.json?query=' + query;
},
transformResult: function(response, query) {
response = JSON.parse(response);
return {
query: query,
suggestions: $.map(response, function(item) {
return {value: item.position_title, data: {location: item.locations[0]}};
})
}
},
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
},
deferRequestBy: 500,
groupBy: 'location'
});
NYI