Amazonish Search

Using typeahead in bootstrap

by peterbenoit

HTML

<link rel="stylesheet" href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css">
<script src="http://getbootstrap.com/2.3.2/assets/js/bootstrap-typeahead.js "></script>
<script src="http://underscorejs.org/underscore.js"></script>
search for: the...
<br />
<input type="text" data-provide="typeahead" data-items="4" data-source='' autocomplete="off"><span id="category"></span>

CSS

.dropdown-menu > .active > a, 
.dropdown-menu > .active > a, .dropdown-menu > .active > a:hover, .dropdown-menu > .active > a:focus {
    background: #f0f0f0;
    background-image: none;
    color: #000;
}

.category {
    color:#555;
}

JavaScript

$(':input').typeahead({
    minLength: 2,
    source: function(query, process) {
        objects = [],
        map = {},
        data = [
            {
              	"itemId":"1",
             	"label":"The Hobbit",
             	"categoryId":"0",
             	"categoryLabel":""
            },
            {
              	"itemId":"1",
             	"label":"The Hobbit",
             	"categoryId":"1",
             	"categoryLabel":"Movies & TV"
            },
            {
              	"itemId":"1",
             	"label":"The Hobbit",
             	"categoryId":"2",
             	"categoryLabel":"Books"
            },
            {
              
              	"itemId":"4",
              	"label":"The Hobbit",
              	"categoryId":"3",
              	"categoryLabel":"Images & Art"
            },
            {
              
              	"itemId":"5",
              	"label":"The Lord of the Rings",
              	"categoryId":"2",
              	"categoryLabel":"Books"
            }
           ] 
        $.each(data, function(i, object) {
            var lbl;
            if(object.categoryLabel.length > 0) {
                lbl = object.label + " - " + object.categoryLabel;
            }
            else {
                lbl = object.label + " " + object.categoryLabel;
            }
            map[lbl] = object;
          	objects.push(lbl); 
        });

        process(objects);
    },
    updater: function(item) {
        $("#category").text('');
        if(map[item].categoryLabel.length > 0) {
            $("#category").text(" in " + map[item].categoryLabel);
        }
        return map[item].label;
    }
});