2017-08-21 8 views
0

質問ユーザーがリストから状態を選択すると、状態の値を取得したいと思います。私はこれまで、次のいる:しかし、結果はすべての時間を節約しているユーザーが値を選択しているユーザーが文字ではなく:それはこのように思えるユーザーが結果を選択した場合にのみ、typeahead.jsの結果を保存する方法は?

$('form').on("change", ".state", function(e){ 
    var $contextualDiv = $(e.target).closest('div'); 
    var $state = $contextualDiv.find('.state'); 
    $state.each(function(i,v){ 
     console.log($(v).val()); 
    }); 
    ... 

もアクセスするための正しい方法ではありませんオブジェクトを介して選択されます。ドキュメントに基づいて、私はちょうどラインを介してそれをつかむことができる必要があります:

var $ state = $( '。state')。typeahead( 'val');

これは私の現在のコードです:

HTML:

<form> 
    <div> 
     <input class="state tt-input"> 
    </div> 
    ... 
</form> 

jqueryの/ typeahead.js実装:

<script> 
    $(document).ready(function() { 

    var bh = new Bloodhound({ 
     datumTokenizer: Bloodhound.tokenizers.whitespace, 
     queryTokenizer: Bloodhound.tokenizers.whitespace, 
     prefetch: { 
      url: '/get_states/', 
      prefetch: function(settings) { 
      settings.type = "GET"; 
      return settings; 
      }, 
     }, 
     }); 

    $('.state').typeahead({ 
     hint: true, 
     highlight: true, 
     minLength: 1 
    }, 
    { 
     name: 'states', 
     source: bh, 
    }); 

    var substringMatcher = function(strs) { 
     return function findMatches(q, cb) { 
     var matches, substringRegex; 

     // an array that will be populated with substring matches 
     matches = []; 

     // regex used to determine if a string contains the substring `q` 
     substrRegex = new RegExp(q, 'i'); 

     // iterate through the pool of strings and for any string that 
     // contains the substring `q`, add it to the `matches` array 
     $.each(strs, function(i, str) { 
     if (substrRegex.test(str)) { 
      matches.push(str); 
     } 
     }); 

     cb(matches); 
    }; 
    }; 

における '状態' で変数 '航空会社' を交換してくださいピクチャー。 Typeahead object

Value is correct.

答えて

0

先行入力ライブラリーは、ユーザーがオプションを選択したイベントをトリガします。そのイベントの名前はtypeahead:selectです。あなたの実装のために働くためにこれを適応することができ

$('.typeahead').bind('typeahead:select', function(ev, suggestion) { 
    console.log('Selection: ' + suggestion); 
}); 

:ここdocumentationに提供された例があります。

私はこれが動作すると思います

$('form input.state').on("typeahead:select", function(e, suggestion) { 
    console.log("Selection: ", suggestion); 
    // OR 
    // console.log("Selection", $(this).typeahead("val")); 
}); 
+0

私はあなたに提案するものに変更している:$ state.bind( '先行入力:SELECT'、機能(EV、提案){ はconsole.log( '選択: '+ suggestion); });しかし、私は提案があります:未定義のエラー。 $ stateとしてオブジェクトを保存することはできませんか? –

+0

@HC答えを編集して例を挙げました。 – Titus

+0

あなたのご協力ありがとうございました。私はあなたの解決策を試しましたが、私は「未定義」の結果に過ぎません。 'Uncaught TypeError:プロパティ' type 'of undefinedを読み取ることができません' jsfiddleを作成しました。まだ何が問題なのか分かりません。 https://jsfiddle.net/tj7dremL/11/ –

関連する問題