jQuery Autocomplete with Table Results

jQuery Autocomplete with Table Results

by oterox

HTML

<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div id="project-label">Selecciona destino:</div>
<input id="project">
<input type="hidden" id="project-id">
<p id="description"></p>

CSS

#description {
  margin: 0;
  padding: 0;
}

JavaScript

$(function() {
  //random json values
  var destinos = [{
    id: 1,
    value: "Granada",
  }, {
    id: 65,
    value: "Madrid",
  }, {
    id: 235,
    value: "Barcelona",
  }, {
    id: 78,
    value: "Lanzarote",
  }, {
    id: 75,
    value: "Bilbao",
  }, {
    id: 124,
    value: "Sevilla",
  }, {
    id: 1233,
    value: "Zaragoza",
  }, {
    id: 244,
    value: "Cadiz",
  }];

  $.widget("custom.tablecomplete", $.ui.autocomplete, {
    _create: function() {
      this._super();
      this.widget().menu("option", "items", "> tr:not(.ui-autocomplete-header)");
    },
    _renderMenu(ul, items) {
      var self = this;
      //table definitions
      
      $.each(items, function(index, item) {
        self._renderItemData(ul, $t.find("tbody"), item);
      });
    },
    _renderItemData(ul, table, item) {
      return this._renderItem(table, item).data("ui-autocomplete-item", item);
    },
    _renderItem(table, item) {
      var $row = $("<tr>", {
        class: "ui-menu-item",
        role: "presentation"
      })
      $("<td>").html(item.id).appendTo($row);
      $("<td>").html(item.value).appendTo($row);
      return $row.appendTo(table);
    }
  });

  function _doFocusStuff(event, ui) {
    if (ui.item) {
      console.log(ui.item);
      var $item = ui.item;
      $("#project").val($item.value);
      $("#project-id").val($item.id);
    }
    return false;
  }

  // create the autocomplete
  var autocomplete = $("#project").tablecomplete({
    minLength: 1,
    source: destinos,
    //focus: _doFocusStuff
  });

  // get a handle on it's UI view
  var autocomplete_handle = autocomplete.data("ui-autocomplete");
});