简体   繁体   中英

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;
        }
    }
});

Seems you are using jQuery-UI autocomplete syntax. Typeahed use Bloodhound suggestion engine. Check Typeahead documentation . Hearing Typeahead custom-event: typeaead:selected let ou retrieve the jQuery event object, the suggestion object, and the name of the dataset the suggestion belongs to.

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,
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM