25

There are a lot of typeahead ajax examples out there for bootstrap 2, for example this here twitter bootstrap typeahead ajax example.

However I am using bootstrap 3 and I could not find a complete example, instead there are just a bunch of incomplete information snippets with links to other websites, for example this here Where is the typeahead JavaScript module in Bootstrap 3 RC 1?

Could someone please post a fully working example on how to use typeahead with bootstrap 3, if you load the data from the server via ajax, every time the user changes the input.

Community
  • 1
  • 1
Pascal Klein
  • 23,665
  • 24
  • 82
  • 119

5 Answers5

40

With bootstrap3-typeahead, I made it to work with the following code:

<input id="typeahead-input" type="text" data-provide="typeahead" />

<script type="text/javascript">
jQuery(document).ready(function() {
    $('#typeahead-input').typeahead({
        source: function (query, process) {
            return $.get('search?q=' + query, function (data) {
                return process(data.search_results);
            });
        }
    });
})
</script>

The backend provides search service under the search GET endpoint, receiving the query in the q parameter, and returns a JSON in the format { 'search_results': ['resultA', 'resultB', ... ] }. The elements of the search_resultsarray are displayed in the typeahead input.

Scott Solmer
  • 3,871
  • 6
  • 44
  • 72
Michael
  • 689
  • 9
  • 13
4

Here is my step by step experience, inspired by typeahead examples, from a Scala/PlayFramework app we are working on.

In a script LearnerNameTypeAhead.coffee (convertible of course to JS) I have:

$ ->
  learners = new Bloodhound(
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value")
    queryTokenizer: Bloodhound.tokenizers.whitespace
    remote: "/learner/namelike?nameLikeStr=%QUERY"
  )
  learners.initialize()
  $("#firstName").typeahead 
    minLength: 3
    hint: true
    highlight:true
   ,
    name: "learners"
    displayKey: "value"
    source: learners.ttAdapter()

I included the typeahead bundle and my script on the page, and there is a div around my input field as follows:

<script src=@routes.Assets.at("javascripts/typeahead.bundle.js")></script>
<script src=@routes.Assets.at("javascripts/LearnerNameTypeAhead.js") type="text/javascript" ></script>
<div>
  <input name="firstName" id="firstName" class="typeahead" placeholder="First Name" value="@firstName">
</div>

The result is that for each character typed in the input field after the first minLength (3) characters, the page issues a GET request with a URL looking like /learner/namelike?nameLikeStr= plus the currently typed characters. The server code returns a json array of objects containing fields "id" and "value", for example like this:

[ {
    "id": "109",
    "value": "Graham Jones"
  },
  {
    "id": "5833",
    "value": "Hezekiah Jones"
} ]

For play I need something in the routes file:

GET /learner/namelike controllers.Learners.namesLike(nameLikeStr:String)

And finally, I set some of the styling for the dropdown, etc. in a new typeahead.css file which I included in the page's <head> (or accessible .css)

.tt-dropdown-menu {
  width: 252px;
  margin-top: 12px;
  padding: 8px 0;
  background-color: #fff;
  border: 1px solid #ccc;
  border: 1px solid rgba(0, 0, 0, 0.2);
  -webkit-border-radius: 8px;
     -moz-border-radius: 8px;
          border-radius: 8px;
  -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
     -moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
          box-shadow: 0 5px 10px rgba(0,0,0,.2);
}
.typeahead {
  background-color: #fff;
}
.typeahead:focus {
  border: 2px solid #0097cf;
}
.tt-query {
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
     -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.tt-hint {
  color: #999
}
.tt-suggestion {
  padding: 3px 20px;
  font-size: 18px;
  line-height: 24px;
}
.tt-suggestion.tt-cursor {
  color: #fff;
  background-color: #0097cf;
}
.tt-suggestion p {
  margin: 0;
}
wwkudu
  • 2,778
  • 3
  • 28
  • 41
  • where did you get the styles from? With out them, it is terrible in my BS-3 project. With the styles, it looks great. – raider33 Sep 07 '14 at 00:45
  • @raider33 I think I got them from inspecting the page at [Twitter Typeahead Examples](https://twitter.github.io/typeahead.js/examples/). I may have had to adjust slightly to fit with my project styles. – wwkudu Sep 08 '14 at 08:43
  • What is this Bloodhound Class? And could you please reather post javascript then coffeescript. I know I could convert it, but I think everybody wo can read coffee, can read plain javascript, but not the other way round. – Pascal Klein Sep 16 '14 at 09:04
  • @PascalKlein Bloodhound is the suggestion engine, the code that decides which options to bring back based on what has been typed so far. More docs at the [TypeAhead page](https://github.com/twitter/typeahead.js/). In their words, there are two parts to type ahead: the UI view (Typeahead) and the suggestion engine (in this case Bloodhound). – wwkudu Sep 16 '14 at 09:27
  • Thanks for your example. "making sure that the div id, not the input id, is the one referred to in the script" -> you're actually referring to `$("#getLearnerLike .typeahead")`, which is the input field within that div. – Christof May 01 '16 at 10:47
3

I'm using this https://github.com/biggora/bootstrap-ajax-typeahead

The result of code using Codeigniter/PHP

<pre>

$("#produto").typeahead({
        onSelect: function(item) {
            console.log(item);
            getProductInfs(item);
        },
        ajax: {
            url: path + 'produto/getProdName/',
            timeout: 500,
            displayField: "concat",
            valueField: "idproduto",
            triggerLength: 1,
            method: "post",
            dataType: "JSON",
            preDispatch: function (query) {
                showLoadingMask(true);
                return {
                    search: query
                }
            },
            preProcess: function (data) {

                if (data.success === false) {
                    return false;
                }else{
                    return data;    
                }                
            }               
        }
    });
</pre>   
Scott Solmer
  • 3,871
  • 6
  • 44
  • 72
1

Here you can find info on how to upgrade to v3: http://tosbourn.com/2013/08/javascript/upgrading-from-bootstraps-typeahead-to-typeahead-js/

Here are some examples too: http://twitter.github.io/typeahead.js/examples/

netcult
  • 167
  • 1
  • 1
  • 11
  • 3
    What do you mean upgrading? Can you rather please just enter a valid example here. – Pascal Klein Apr 16 '14 at 10:33
  • I meant if you have a working typeahead for bootstrap2, you can upgrade using this info. The second link might be more helpfull for you? – netcult Apr 16 '14 at 14:45
  • 1
    That link is dead, please put content in the answer, rather than linking to it externally. – Keith Apr 07 '16 at 13:50
-1
<input id="typeahead-input" type="text" data-provide="typeahead" />

<script type="text/javascript">
var data = ["Aamir", "Amol", "Ayesh", "Sameera", "Sumera", "Kajol", "Kamal",
  "Akash", "Robin", "Roshan", "Aryan"];
$(function() {
    $('#typeahead-input').typeahead({
        source: function (query, process) {
               process(data);
            });
        }
    });
});
</script>