Dinesh P.R.
Dinesh P.R.

Reputation: 7276

Twitter Bootstrap TypeAhead to work like DropDown List / Select Tag with Autocomplete Feature

I want to have a DropDown List / < Select > HTML Tag behaviour with AutoComplete Feature using Twitter Bootstrap TypeAhead. The link here achieves the feature of Combo Box where user can provide his own input also. I want to restrict the User to select only from the option provided. Is there any way to tweek the Twitter Bootstrap TypeAhead Plugin to emulate the behaviour of DropDown List / Tag with Autocomplete Feature.

I have referred the Following question before posting

  1. Adding a dropdown button to Twitter bootstrap typeahead component

Upvotes: 29

Views: 63391

Answers (3)

mike nelson
mike nelson

Reputation: 22176

I just found this awesome plugin that turns a standard SELECT element into very seamless nicely styled combo box using bootstrap typeahead. It looks really good, I'm going to use it on my next project.

https://github.com/danielfarrell/bootstrap-combobox

Live Example (Bootstrap 3)

Upvotes: 24

d4kris
d4kris

Reputation: 538

Tiny improvement to davidkonrads answer to keep the filter functionality when typing.

$(document).ready(function() {

$("#test").typeahead({
    "source": ['Pennsylvania', 'Connecticut', 'New York', 'Maryland', 'Virginia'],
    //match any item
    matcher: function(item) {
        if (this.query == '*') {
            return true;
        } else {
            return item.indexOf(this.query) >= 0;
        }
    },
    //avoid highlightning of "*"
    highlighter: function(item) {
        return "<div>" + item + "</div>"
    }
});

// "select"-button
$(".showAll").click(function(event) {
    var $input = $("#test");
    //add something to ensure the menu will be shown
    $input.val('*');
    $input.typeahead('lookup');
    $input.val('');
});

});

http://jsfiddle.net/d4kris/5rtGA/3/

Upvotes: 10

davidkonrad
davidkonrad

Reputation: 85598

That is indeed possible - even very simple - without changing the typeahead javascript / using altered code, IF you are willing not to show matched results highlighted.

HTML:

<input name="test" id="test"/>
<button id="emu-select" class="btn btn-small" type="button">
<i class="icon-arrow-down"></i>
</button>

script:

$(document).ready(function() {

    $("#test").typeahead({
        "source": ['Pennsylvania','Connecticut','New York','Maryland','Virginia'],
        //match any item
        matcher : function (item) {
            return true;
        },
        //avoid highlightning of "a"
        highlighter: function (item) {
            return "<div>"+item+"</div>"
        }
    });

    // "select"-button
    $("#emu-select").click(function(){
        //add something to ensure the menu will be shown
        $("#test").val('a');
        $("#test").typeahead('lookup');
        $("#test").val('');
    });
});

working code / example at jsfiddle http://jsfiddle.net/davidkonrad/ZJMBE/3/

Upvotes: 6

Related Questions