2
0
mirror of https://github.com/devbridge/jQuery-Autocomplete.git synced 2024-11-29 08:14:06 +00:00
jQuery-Autocomplete/scripts/demo.js
Polo 80e940ffff Added an optional no-suggestions notice when no matching results
This feature aims to improve user experience and plugin's responsiveness
by providing instant feedback for empty searches.
2014-03-26 11:51:46 -07:00

70 lines
2.4 KiB
JavaScript

/*jslint browser: true, white: true, plusplus: true */
/*global $, countries */
$(function () {
'use strict';
var countriesArray = $.map(countries, function (value, key) { return { value: value, data: key }; });
// Setup jQuery ajax mock:
$.mockjax({
url: '*',
responseTime: 2000,
response: function (settings) {
var query = settings.data.query,
queryLowerCase = query.toLowerCase(),
re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi'),
suggestions = $.grep(countriesArray, function (country) {
// return country.value.toLowerCase().indexOf(queryLowerCase) === 0;
return re.test(country.value);
}),
response = {
query: query,
suggestions: suggestions
};
this.responseText = JSON.stringify(response);
}
});
// Initialize ajax autocomplete:
$('#autocomplete-ajax').autocomplete({
// serviceUrl: '/autosuggest/service/url',
lookup: countriesArray,
lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
return re.test(suggestion.value);
},
onSelect: function(suggestion) {
$('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
},
onHint: function (hint) {
$('#autocomplete-ajax-x').val(hint);
},
onInvalidateSelection: function() {
$('#selction-ajax').html('You selected: none');
}
});
// Initialize autocomplete with local lookup:
$('#autocomplete').autocomplete({
lookup: countriesArray,
minChars: 0,
onSelect: function (suggestion) {
$('#selection').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
},
showNoSuggestionNotice: true,
noSuggestionNotice: 'Sorry, no matching results',
});
// Initialize autocomplete with custom appendTo:
$('#autocomplete-custom-append').autocomplete({
lookup: countriesArray,
appendTo: '#suggestions-container'
});
// Initialize autocomplete with custom appendTo:
$('#autocomplete-dynamic').autocomplete({
lookup: countriesArray
});
});