jquery ui autocomplete in a nutshell
http://stackoverflow.com/questions/8329697/jquery-ui-autocomplete-clear-previous-search-term
by altano
HTML
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<label for="field_id">ID</label>
<input id="field_id" type="text" style="width: 40px;">
<label for="field">Countries (starting with A)</label>
<input id="field" type="text" style="width: 200px;">
<span id="results_count"></span>
<br>
<p>
<span>(updates when text field changes and focus is moved)</span>
<br />
<span>$("#field").autocomplete("instance").term =</span>
<span id="selected"></span>
</p>
JavaScript
$(function() {
var countries_starting_with_A = [{
"id": "1",
"value": "Afghanistan",
"label": "Afghanistan"
}, {
"id": "17",
"value": "Albania",
"label": "Albania"
}, {
"id": "18",
"value": "Algeria",
"label": "Algeria"
}, {
"id": "20",
"value": "American Samoa",
"label": "American Samoa"
}, {
"id": "22",
"value": "Andorra",
"label": "Andorra"
}, {
"id": "10",
"value": "Angola",
"label": "Angola"
}, {
"id": "11",
"value": "Anguilla",
"label": "Anguilla"
}, {
"id": "23",
"value": "Antarctica",
"label": "Antarctica"
}, {
"id": "24",
"value": "Antigua and Barbuda",
"label": "Antigua and Barbuda"
}, {
"id": "25",
"value": "Argentina",
"label": "Argentina"
}, {
"id": "26",
"value": "Armenia",
"label": "Armenia"
}, {
"id": "27",
"value": "Aruba",
"label": "Aruba"
}, {
"id": "28",
"value": "Australia",
"label": "Australia"
}, {
"id": "29",
"value": "Austria",
"label": "Austria"
}, {
"id": "12",
"value": "Azerbaijan",
"label": "Azerbaijan"
}];
$("#field").autocomplete({
source: countries_starting_with_A,
minLength: 1,
select: function(event, ui) {
// feed hidden id field
$("#field_id").val(ui.item.id);
// update number of returned rows
$('#results_count').html('');
},
open: function(event, ui) {
// update number of returned rows
var len = $('.ui-autocomplete > li').length;
$('#results_count').html('(#' + len + ')');
},
close: function(event, ui) {
// update number of returned rows
$('#results_count').html('');
},
// mustMatch implementation
change: function(event, ui) {
if (ui.item === null) {
$(this).val('');
$('#field_id').val('');
}
var term = $("#field").autocomplete("instance").term;
$("#selected").text(term);
}
...