Typeahead Categories

by Kyle Mitofsky

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.5/typeahead.bundle.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="http://kylemitofsky.com/libraries/libraries/typeahead.default.css">

<input type="text" value="" id="cname" 
       placeholder="Type letter e here" 
       class="typeahead form-control" />
        













<!-- Post Info -->
<div style='position:fixed;bottom:0;left:0; background:lightgray;width:100%;'>
    About this SO Question:
    <a href='http://stackoverflow.com/q/25419972/1366033'>
        Twitter typeahead add custom data to dataset
    </a>
</div>

CSS

body {
    margin: 15px;
}
.typeahead-group {
  margin: 0 20px 5px 10px;
  padding: 3px 0;
  border-bottom: 1px solid #ccc;
}

JavaScript

var movies = [{
        "id": "38",
        "value": "Entertaintment",
        "parent_id": "27",
        "children": "1",
        "childCategories": [{
            "id": "28",
            "value": "Movies",
            "parent_id": "38"
        }, {
            "id": "29",
            "value": "Sports",
            "parent_id": "38"
        }]
    }, {
        "id": "40",
        "value": "eeen",
        "parent_id": "27",
        "children": "1",
        "childCategories": [{
            "id": "41",
            "value": "een child 1",
            "parent_id": "40"
        }]
    }, {
        "id": "41",
        "value": "een parent 1",
        "parent_id": "40",
        "children": "0",
        "childCategories": false
    }];

var dataSources = [];
var ungrouped = [];

$.each(movies, function(index, movieItem) {
    if (movieItem.childCategories) {
        
        var bloodhoundEngine = createBlounhoud(movieItem.childCategories, 'value');
        var dataSource = {
            name: movieItem.value,
            displayKey: 'value',
            source: bloodhoundEngine.ttAdapter(),
            templates: {
                header: '<h3 class="typeahead-group">'+movieItem.value+'</h3>'
            }
        };
        dataSources.push(dataSource);
    } else {
        ungrouped.push(movieItem);
    }
});

(function addUngroupedItems() {
    var bloodhoundEngine = createBlounhoud(ungrouped, 'value');
    var dataSource = {
        name: 'ungrouped',
        displayKey: 'value',
        source: bloodhoundEngine.ttAdapter()
    };
    dataSources.unshift(dataSource);
})();

function createBlounhoud(array, datumValue) {
    var bh = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace(datumValue),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        local: array
    });
    bh.initialize();
    return bh;
}

$('#cname').typeahead({ highlight: true }, dataSources);