Search code examples
phpjqueryajaxtwitter-bootstrapbootstrap-typeahead

Passing an object to onSelect using Bootstrap3-typeahead


BootStrap3-TypeAhead

Hey all, I'm having trouble figuring out how I should be passing along an object of anything more than the default to onSelect for more extensive usage. Here's my code, any help would be greatly appreciated!

$("input[type='text']").typeahead({
    onSelect: function(item) {
        // Do things with the item object here.
    },
    items: 10,
    ajax: {
        url: "modules/scripts/Search.php",
        timeout: 500,
        triggerLength: 1,
        method: "POST",
        preDispatch: function (str) {
            return {
                String: str,
                State: $("#"+$("#"+InputBox).attr("data-place")+"StateText").attr("data-sc")
            }
        },
        preProcess: function (data) {
            if (data.success === false) { return false; }
            // I think I'd create the item object here, or pass it along?

            var DD = [];
            $.each(data, function(key, value) {
                DD.push(value['City']+" - "+value['Zip']);
                TempArr[value['ID']] = data[key];
            });

            return DD;
        }
    }
});

Solution

  • I ended up solving this issue using the .remote.filter: function(obj) {} options. Here's a snip:

    var AjaxOptions = {
        type: "POST",
        cache: false,
        data: { limit: 10 },
        beforeSend: function(jqXHR, settings){
            // Manipulate settings.data to send more information than just the query string.
        },
        complete: function(data) {
            // If desired, you could do a 'how long this query took' display here.
        }
    }
    
    var InputArea = new Bloodhound({
        datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.val); },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        limit: 10,
        remote: {
            cache: false,
            url: 'scripts/Query.php?q=%QUERY',
            filter: function (InputArea) {
                return $.map(InputArea, function (data) {
                    // Do whatever you want with 'data', then return it
    
                    return {
                        foo: bar,
                        arnold: data.palmer
                    };
                });
            },
            ajax: AjaxOptions,
        }
    });