web-dev-qa-db-ja.com

Twitterで選択したイベントを処理するbootstrap Typeahead?

ユーザーが値を選択Twitter bootstrap Typeaheadを使用した直後にJavaScript関数を実行したい。

選択したイベントなどを検索します。

20
George Botros
$('.typeahead').on('typeahead:selected', function(evt, item) {
    // do what you want with the item here
})
35
drow
$('.typeahead').typeahead({
    updater: function(item) {
        // do what you want with the item here
        return item;
    }
})
16
Marcilio Leite

次のコード例を参考にして、ここでやりたいことに対して先行入力がどのように機能するかを説明します。

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. ユーザーがアイテムをクリックした場合(またはカーソルキーでアイテムを選択してEnterキーを押した場合)、_updater:_オプションが実行されます。 選択した値でテキストフィールドをまだ更新していないことに注意してください
  4. item変数を使用して選択したアイテムを取得し、それを使用して必要なことを実行できます。 myOwnFunction(item)
  5. 入力フィールド自体に何かをしたい場合に備えて、入力フィールド自体__$fld_への参照を作成する例を含めました。 $(this)を使用してフィールドを参照することはできません。
  6. 君は しなければならない 次に、_return item;_オプション内に_updater:_行を含めて、入力フィールドが実際にitem変数で更新されるようにします。
6
MichaelJTaylor

私が最初にここに回答を投稿したとき(ただし、多くの場合、ここで回答を見つけました)、ここに私の貢献があります。変更を検出できるはずです-これを試してください:

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

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

彼らの documentation によると、selectedイベントを処理する適切な方法は、このイベントハンドラーを使用することです。

$('#selector').on('typeahead:select', function(evt, item) {
    console.log(evt)
    console.log(item)
    // Your Code Here
})
3
Artur Grigio

その機能を含む拡張機能を作成しました。

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

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

}
1