Autocomplete with typeahead.js


Example implementation of an autocomplete form using typeahead.js. The data is retrieved remotely from a JSON file, each item has a ‘ticker’ and ‘name’. Submit is only allowed when an autocomplete element is selected.

Autocomplete


Javascript

$(document).ready(function(){
  var companies = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('ticker'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: {
      url: "company_tickers.json",
      ttl: 1 // in milliseconds
    },
  });

  // Initializing the typeahead with remote dataset
  $('.typeahead').typeahead(null, {
      name: 'companies',
      displayKey: 'ticker',
      source: companies,
      limit: 5,
      //mustSelectItem: true,
      autoselect: true,
      templates: {
        empty: function(context){
          $(".tt-dataset").text('No companies match the current query');
        },
        suggestion: function(data) {
          return '<p style="font-size:15px;padding:3px 20px;margin:0;text-transform:uppercase;"><strong>' + data.ticker + '</strong> – ' + data.name + '</p>';
        }
      },
  });

  // On select
  $('.typeahead').on('typeahead:select', function(e){
    $('#myBtn').prop('disabled', false);
    e.target.form.submit();
  });
  $('.typeahead').keyup(function(e) {
    if ( !(e.key === "Enter") && !(e.key === "ArrowUp") && !(e.key === "ArrowDown")) {
      $('#myBtn').prop('disabled', true);
    }
  });

});

Html

<script src="http://twitter.github.com/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<script src="https://cdn.jsdelivr.net/npm/handlebars@latest/dist/handlebars.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

<div class="bs-example">
  <form class="autocomplete" autocomplete="off" action="" method="get" name="searchForm">
    <div style="position:relative">
      <input type="text" class="form-control typeahead tt-query" autocomplete="off" name="q" id="myInput" spellcheck="false" style="background-color:#fff;text-transform:uppercase;" placeholder="Search...">
      <button type="submit" id="myBtn" class="btn btn-primary" disabled="true" style="background-color:#2196f3;"><div style="-webkit-transform: rotate(45deg); 
                   -moz-transform: rotate(45deg); 
                     -o-transform: rotate(45deg);
                        transform: rotate(45deg);">
        &#9906;
        </div>
      </button>
    </div>
  </form>
</div>

CSS

.bs-example {
  font-family: sans-serif;
  position: relative;
  margin: 10px 0px 100px 100px;
}
.typeahead, .tt-query, .tt-hint {
  border: 2px solid #CCCCCC;
  border-radius: 8px;
  font-size: 15px;
  height: 35px;
  line-height: 30px;
  outline: medium none;
  padding: 8px 12px;
  width: 250px;
}
.typeahead {
  background-color: #FFFFFF;
}
.tt-query {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
}
.tt-hint {
  color: #999999;
}
.tt-menu {
  background-color: #FFFFFF;
  border: 1px solid rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
  margin-top: 12px;
  padding: 8px 0;
  width: 422px;
}
.tt-suggestion {
  font-size: 15px;
  padding: 3px 20px;
}
.tt-suggestion:hover, .tt-cursor {
  cursor: pointer;
  background-color: #e9e9e9;
}
.tt-suggestion p {
  margin: 0;
  font-size:15px;
  padding:3px 20px;
}