Bootstrap - show all Typeahead items on focus

user1736062 picture user1736062 · Oct 10, 2012 · Viewed 35.6k times · Source

I'd like to show all Typeahead items when the text-input (id="Questions") get focus. How can I do it?

Javascript:

function SetTypeahead() {
    $("#Questions").typeahead({
        minLength: 0,
        source: [
                "Q1?",
                "Q2?",
                "Q3?",
                "@4?"
        ]
    });
}

Answer

user1893029 picture user1893029 · Dec 19, 2012

Get the latest bootstrap typeahead plugin v2.1.2 at https://raw.github.com/michaelcox/bootstrap/6789648b36aedaa795f1f5f11b4da6ab869f7f17/js/bootstrap-typeahead.js

This update will allow minLength of zero to enable show all for typeahead

<input id="typeaheadField" name="typeaheadField" type="text" placeholder="Start Typing">

$("#typeaheadField").typeahead({
                        minLength: 0,
                        items: 9999,
                        source: ["Alabama","Alaska","Arizona","Arkansas","California","Colorado", "Oregon"]    
                    });

Then you have to attach the onFocus event to your element, because it's not defined by the plugin:

$("#typeaheadField").on('focus', $("#typeaheadField").typeahead.bind($("#typeaheadField"), 'lookup'));

it's a also a good idea to overwrite the bootstrap typeahead css class locally to set max-height and vertical scroll for the results in case there are too many results.

.typeahead {
max-height: 200px;
overflow-y: auto;
overflow-x: hidden;
}