使用Bootstrap3-typeahead将对象传递给onSelect

时间:2015-01-17 16:25:22

标签: php jquery ajax twitter-bootstrap bootstrap-typeahead

BootStrap3-TypeAhead

嘿所有,我很难弄清楚我应该如何传递超过默认值的对象以便更广泛地使用onSelect。这是我的代码,非常感谢任何帮助!

$("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;
        }
    }
});

2 个答案:

答案 0 :(得分:0)

似乎您正在使用jQuery-UI自动完成语法。键入使用Bloodhound建议引擎。检查Typeahead documentation。 听力Typeahead自定义事件:typeaead:selected让我们检索jQuery事件对象,建议对象以及该建议所属的数据集的名称。

答案 1 :(得分:0)

我最终使用.remote.filter: function(obj) {}选项解决了这个问题。这是一个剪辑:

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