jquery ui autocomplete in a nutshell

by Damith Nuwan Sampath

HTML

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css">
<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;"> &nbsp;&nbsp;&nbsp;
<span id="results_count"></span>
<br>
<br>
<input type="button" value="OK">

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('');
      }
    }
  });

  // mustMatch (no value) implementation
  $("#field").focusout(function() {
    if...