Search This Blog

Thursday, May 7, 2015

Use of typehead.js (autocomplete)

usage: GenerateAutoComplete(selectors.BankName, bankNamesArray); 

var GenerateAutoComplete = function (elementID, data, clear) {
    /* ------ Regular Typeahead autocomplete -------- */
    //var substringMatcher = function (strs) {
    //    return function findMatches(q, cb) {
    //        var matches, substrRegex;

    //        // an array that will be populated with substring matches
    //        matches = [];

    //        // regex used to determine if a string contains the substring `q`
    //        substrRegex = new RegExp(q, 'i');

    //        // iterate through the pool of strings and for any string that
    //        // contains the substring `q`, add it to the `matches` array
    //        $.each(strs, function (i, str) {
    //            if (substrRegex.test(str)) {
    //                // the typeahead jQuery plugin expects suggestions to a
    //                // JavaScript object, refer to typeahead docs for more info
    //                matches.push({ value: str });
    //            }
    //        });

    //        cb(matches);
    //    };
    //};

    //$(elementID).typeahead({
    //    hint: true,
    //    highlight: true,
    //    minLength: 1
    //},
    //{
    //    name: 'data',
    //    displayKey: 'value',
    //    source: substringMatcher(data)
    //});

    /*--------- Bloodhound Search Engine-----------*/
    clear = typeof clear === "undefined" ? true : clear;
    $(elementID).typeahead('destroy');

    if (clear) {
        $(elementID).val('');
    }

    // constructs the suggestion engine
    var bloodHoundData = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        local: $.map(data, function (ddlElement) { return { value: ddlElement }; }),
        limit: 10
    });

    // kicks off the loading/processing of `local` and `prefetch`
    bloodHoundData.initialize();

    $(elementID).typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    },
    {
        name: 'data',
        displayKey: 'value',
        // `ttAdapter` wraps the suggestion engine in an adapter that
        // is compatible with the typeahead jQuery plugin
        source: bloodHoundData.ttAdapter()
    });
}

No comments:

Post a Comment