jQuery Autocomplete with Table Results

jQuery Autocomplete with Table Results

by Twisty

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">Select a project (type "s" for a start):</div>
<input id="project">
<input type="hidden" id="project-id">
<p id="project-description"></p>

CSS

#project-label {
  display: block;
  font-weight: bold;
  margin-bottom: 1em;
}

#project-icon {
  float: left;
  height: 32px;
  width: 32px;
}

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

JavaScript

$(function() {
  //random json values
  var projects = [{
    id: 1,
    value: "Thomas",
    cp: 134
  }, {
    id: 65,
    value: "Richard",
    cp: 1743
  }, {
    id: 235,
    value: "Harold",
    cp: 7342
  }, {
    id: 78,
    value: "Santa Maria",
    cp: 787
  }, {
    id: 75,
    value: "Gunner",
    cp: 788
  }, {
    id: 124,
    value: "Shad",
    cp: 124
  }, {
    id: 1233,
    value: "Aziz",
    cp: 3544
  }, {
    id: 244,
    value: "Buet",
    cp: 7847
  }];

  $.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
      var $t = $("<table>", {
        border: 1
      }).appendTo(ul);
      $t.append($("<thead>"));
      $t.find("thead").append($("<tr>", {
        class: "ui-autocomplete-header"
      }));
      var $row = $t.find("tr");
      $("<th>").html("ID#").appendTo($row);
      $("<th>").html("Name").appendTo($row);
      $("<th>").html("Cool Point").appendTo($row);
      $("<tbody>").appendTo($t);
      $.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);
      $("<td>").html(item.cp).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);
      $("#project-description").html($item.cp);
    }
    return false;
  }

  // create the...