javascripttypeahead.jstypeaheadbootstrap-typeaheadtwitter-typeahead

Typeahead.js not showing suggestions


I am trying to make typeahead for the input box. I'm using typeahead.js for that. I'm using the same code to learn this functionality. Though I'm not getting any error, it is not showing suggestions. I've also included all the scripts that are required which are as follows:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="the-basics.js"></script>

The Html is as follows:

<div class="container">
<div id="the-basics">
  <input class="typeahead" type="text" placeholder="States of USA">
</div>
  </div>

The js is as follows:

var substringMatcher = function(strs) {
console.log('strs', strs);
return function findMatches(q, cb) {
  console.log('q', q);
  var matches, substringRegex;

  // an array that will be populated with substring matches
  matches = [];
  console.log('matches', matches);

  // regex used to determine if a string contains the substring `q`
  substrRegex = new RegExp(q, 'i');

  // iterate through the pool of strings and for any string that
  // contains the substring `q`, add it to the `matches` array
  $.each(strs, function(i, str) {
    if (substrRegex.test(str)) {
      matches.push(str);
    }
  });
  
  console.log('matches', matches);

  cb(matches);
};


};
  
  var states = ['Alabama', 'Alaska', 'Arizona', 'California',
    'Colorado', 'Connecticut', 'Delaware', 'Florida'
  ];
  
  $('#the-basics .typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 1
  },
  {
    name: 'states',
    source: substringMatcher(states)
  });

Please help me in resolving this.

PS: I've tried different solutions that are there on StackOverflow like this but it is not working for me.


Solution

  • const states = [
      "Alabama",
      "Alaska",
      "Arizona",
      "California",
      "Colorado",
      "Connecticut",
      "Delaware",
      "Florida"
    ];
    
    $("#the-basics .typeahead").typeahead({
      hint: true,
      highlight: true,
      minLength: 1,
      name: "states",
      source: states
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    
    
    <div class="container">
      <div id="the-basics">
        <input class="typeahead" type="text" placeholder="States of USA" autocomplete="off">
      </div>
    </div>