2017-08-09 118 views
1

問題一旦用戶從列表中選擇一個狀態,我想獲取狀態的值。到目前爲止,我似乎沒有工作。如何在用戶從typeahead.js中選擇結果後保存值?

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

$ state.val()似乎是我無法訪問的類型提前對象。我也不希望用戶在jquery保存值之前單擊輸入框外部,只要用戶從建議列表中選擇一個結果即可。

這是我當前的代碼:

HTML:

的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

嘗試console.log($state.typeahead('val'))

看到documentation

在這種情況下,你有對象的數組來獲取值,你做一個循環:

$state.each(function(i,v){ 
    console.log($(v).val());//or console.log($(v).typeahead('val')) 
}) 

得到ØNLY當前狀態發生了改變你請執行以下操作:

$('form').on("change", ".state", function(e){ 
    console.log($(this).val()); 
    ... 
+0

我嘗試過,但仍得到對象no價值。 –

+0

難道你不能從對象中獲得價值,你可以在你的問題中粘貼對象嗎? – madalinivascu

+0

不知道該怎麼做。它在我的瀏覽器中的Java控制檯中。 –