25

我想在用户使用自动完成文本框引导 Typeahead选择一个值后立即运行 JavaScript 函数。

我正在寻找类似选定事件的东西。

4

9 回答 9

45
$('.typeahead').on('typeahead:selected', function(evt, item) {
    // do what you want with the item here
})
于 2013-03-28T04:55:52.523 回答
16
$('.typeahead').typeahead({
    updater: function(item) {
        // do what you want with the item here
        return item;
    }
})
于 2012-12-25T00:14:47.410 回答
7

有关 typeahead 用于您想要在此处执行的操作的方式的说明,请使用以下代码示例:

HTML 输入框:

<input type="text" id="my-input-field" value="" />

JavaScript 代码块:

$('#my-input-field').typeahead({
    source: function (query, process) {
        return $.get('json-page.json', { query: query }, function (data) {
            return process(data.options);
        });
    },
    updater: function(item) {
        myOwnFunction(item);
        var $fld = $('#my-input-field');
        return item;
    }
})

解释:

  1. 您的输入字段设置为第一行的输入字段:$('#my-input-field').typeahead(
  2. 输入文本时,它会触发source:获取 JSON 列表并将其显示给用户的选项。
  3. 如果用户单击一个项目(或使用光标键选择它并输入),它就会运行该updater:选项。请注意,它尚未使用所选值更新文本字段
  4. 您可以使用变量抓取所选项目item并使用它做您想做的事情,例如myOwnFunction(item).
  5. 我已经包含了一个创建对输入字段本身的引用的示例$fld,以防您想对它做些什么。请注意,您不能使用 $(this) 引用该字段
  6. 然后,您必须return item;在选项中包含该行,updater:以便输入字段实际使用item变量进行更新。
于 2013-05-30T10:49:48.353 回答
5

我第一次在这里发布答案(虽然很多次我在这里找到了答案),所以这是我的贡献,希望它有所帮助。您应该能够检测到更改 - 试试这个:

function bob(result) {
    alert('hi bob, you typed: '+ result);
}

$('#myTypeAhead').change(function(){
    var result = $(this).val()
    //call your function here
    bob(result);
});
于 2012-03-21T22:17:45.247 回答
4

根据他们的文档,处理selected事件的正确方法是使用此事件处理程序:

$('#selector').on('typeahead:select', function(evt, item) {
    console.log(evt)
    console.log(item)
    // Your Code Here
})
于 2016-07-17T18:12:14.053 回答
1

我创建了一个包含该功能的扩展。

https://github.com/tcrosen/twitter-bootstrap-typeahead

于 2012-04-04T00:23:27.907 回答
1

对我有用的如下:

$('#someinput').typeahead({ 
    source: ['test1', 'test2'], 
    afterSelect: function (item) {
        // do what is needed with item
        //and then, for example ,focus on some other control
        $("#someelementID").focus();
    }
});

解决方案取自https://www.py4u.net/discuss/907420

于 2021-10-19T20:31:08.680 回答
0
source:  function (query, process) {
    return $.get(
        url, 
        { query: query }, 
        function (data) {
            limit: 10,
            data = $.parseJSON(data);
            return process(data);
        }
    );
},
afterSelect: function(item) {
    $("#divId").val(item.id);
    $("#divId").val(item.name);

}
于 2017-09-14T20:45:39.640 回答
0

带有一些技巧的完整示例。假设您正在搜索商标,并且想要获取所选的商标 ID。

在您看来 MVC,

@Html.TextBoxFor(model => model.TrademarkName, new { id = "txtTrademarkName", @class = "form-control",
   autocomplete = "off", dataprovide = "typeahead" })
@Html.HiddenFor(model => model.TrademarkId, new { id = "hdnTrademarkId" })

html

<input type="text" id="txtTrademarkName" autocomplete="off" dataprovide="typeahead" class="form-control" value="" maxlength="100" />
<input type="hidden" id="hdnTrademarkId" />

在您的 JQuery 中,

$(document).ready(function () {
var trademarksHashMap = {};
var lastTrademarkNameChosen = "";

$("#txtTrademarkName").typeahead({
    source: function (queryValue, process) {
        // Although you receive queryValue, 
        // but the value is not accurate in case of cutting (Ctrl + X) the text from the text box.
        // So, get the value from the input itself.
        queryValue = $("#txtTrademarkName").val();
        queryValue = queryValue.trim();// Trim to ignore spaces.

        // If no text is entered, set the hidden value of TrademarkId to null and return.
        if (queryValue.length === 0) {
            $("#hdnTrademarkId").val(null);
            return 0;
        }

        // If the entered text is the last chosen text, no need to search again.
        if (lastTrademarkNameChosen === queryValue) {
            return 0;
        }

        // Set the trademarkId to null as the entered text, doesn't match anything.
        $("#hdnTrademarkId").val(null);

        var url = "/areaname/controllername/SearchTrademarks";
        var params = { trademarkName: queryValue };

        // Your get method should return a limited set (for example: 10 records) that starts with {{queryValue}}.
        // Return a list (of length 10) of object {id, text}.
        return $.get(url, params, function (data) {
            // Keeps the current displayed items in popup.
            var trademarks = [];

            // Loop through and push to the array.
            $.each(data, function (i, item) {
                var itemToDisplay = item.text;
                trademarksHashMap[itemToDisplay] = item;
                trademarks.push(itemToDisplay);
            });

            // Process the details and the popup will be shown with the limited set of data returned.
            process(trademarks);
        });
    },
    updater: function (itemToDisplay) {

        // The user selectes a value using the mouse, now get the trademark id by the selected text. 
        var selectedTrademarkId = parseInt(trademarksHashMap[itemToDisplay].value);
        $("#hdnTrademarkId").val(selectedTrademarkId);

        // Save the last chosen text to prevent searching if the text not changed.
        lastTrademarkNameChosen = itemToDisplay;

        // return the text to be displayed inside the textbox.
        return itemToDisplay;
    }
  });

});
于 2022-02-17T09:49:16.390 回答