在twitter bootstrap Typeahead处理选定的事件?

Geo*_*ros 19 javascript jquery events twitter-bootstrap jquery-events

我想在用户使用twitter bootstrap Typeahead 选择一个值后运行javascript函数

我搜索一些像选定的事件

dro*_*row 35

$('.typeahead').on('typeahead:selected', function(evt, item) {
    // do what you want with the item here
})
Run Code Online (Sandbox Code Playgroud)

  • https://github.com/twitter/typeahead.js与Bootstrap typeahead不同 (2认同)

Mar*_*ite 16

$('.typeahead').typeahead({
    updater: function(item) {
        // do what you want with the item here
        return item;
    }
})
Run Code Online (Sandbox Code Playgroud)


Mic*_*lor 7

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

HTML输入字段:

<input type="text" id="my-input-field" value="" />
Run Code Online (Sandbox Code Playgroud)

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;
    }
})
Run Code Online (Sandbox Code Playgroud)

说明:

  1. 您的输入字段设置为第一行的预先输入字段: $('#my-input-field').typeahead(
  2. 输入文本时,它会触发source:获取JSON列表并将其显示给用户的选项.
  3. 如果用户单击某个项目(或使用光标键选择并输入),则会运行该updater:选项.请注意,它尚未使用所选值更新文本字段.
  4. 您可以使用item变量获取所选项目,并根据需要执行所需操作,例如myOwnFunction(item).
  5. 我已经包含了一个创建对输入字段本身的引用的示例$fld,以防您想要对它执行某些操作.请注意,您不能使用$(this)引用该字段.
  6. 然后,您必须return item;updater:选项中包含该行,以便实际使用item变量更新输入字段.


小智 5

我第一次在这里发布了答案(很多时候我在这里找到了答案),所以这是我的贡献,希望它有所帮助.你应该能够检测到一个变化 - 试试这个:

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

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