使用Bootstrap Typeahead如何处理自动完成文本框中的选定事件?

27

我希望在用户使用Bootstrap Typeahead自动完成文本框选择一个值后,立即运行JavaScript函数。

我正在寻找类似于“selected”事件的内容。


1
请看链接:https://dev59.com/32kx5IYBdhLWcg3wA_tS#11747290 - Laurent Debricon
正确答案并不是被选中的那个... :( - Abhishek
9个回答

46
$('.typeahead').on('typeahead:selected', function(evt, item) {
    // do what you want with the item here
})

这种方法适用于 https://twitter.github.io/typeahead.js/,而不适用于 Twitter Bootstrap。(typeahead 现在已从 Twitter Bootstrap 中分离出来) - Ruwanka De Silva
有没有办法在此处理程序中获取按下的键?evt变量似乎没有“which”属性。 - HussienK

19
$('.typeahead').typeahead({
    updater: function(item) {
        // do what you want with the item here
        return item;
    }
})

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. 然后,您必须updater:选项中包含return item;这一行,以便实际使用item变量更新输入字段。

5

这是我第一次在这里发布答案(之前在这里找到过很多答案),以下是我的贡献,希望能够帮助到您。您应该可以检测到变化-请尝试:

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

$('#myTypeAhead').change(function(){
    var result = $(this).val()
    //call your function here
    bob(result);
});

1
因为这不是处理typeahead中所选元素的支持或推荐方式,所以已将其标记为下调,请参见此处:https://github.com/twitter/typeahead.js at: typahead:selected - Oddman

4
根据他们的 文档,处理selected事件的正确方式是使用以下事件处理程序:
$('#selector').on('typeahead:select', function(evt, item) {
    console.log(evt)
    console.log(item)
    // Your Code Here
})

3

以下是我用过的方法:

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

1
链接已失效。 - therealrodk
没问题,解决方案已经从那里复制了。我将删除链接。 - Imran Zahoor

1

1
链接现在失效了。这是代码库吗?https://github.com/tcrosen/twitter-bootstrap-typeahead - tsellon
抱歉,我之前更新了链接,截至4月29日它可以使用。 - Terry

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

}

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

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接