2014-03-29 49 views
2

我需要弄清楚如何使用twitter typeahead.js從json數組中選擇控件中的選項。 [這是一個bootstrap3網站]如何使用twitter typeahead.js從json數組中選擇控件中的選項

我typeahead.js很輕鬆地工作,幾乎默認:

var countries = new Bloodhound({ 
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'), 
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
    limit: 10, 
    prefetch: { 
    url: '[[!~36]]', 
    filter: function(list) { 
     return $.map(list, function(country) { return { name: country }; }); 
    } 
    } 
}); 

countries.initialize(); 


$('#scrollable-typeahead .typeahead').typeahead(null, { 
    name: 'countries', 
    displayKey: 'name', 
    source: countries.ttAdapter() 
}); 

URL指向返回JSON格式的數組鏌鋣資源:

[ 
    { 
     "id": 59, 
     "label": "fname lname 561280" 
    }, 

..... shortened ..... 

    { 
     "id": 73, 
     "label": "fname lname 333333" 
    } 
] 

和我的HTML看起來像:

<span id="scrollable-typeahead"> 
<input type="text" placeholder="Candidate search" class="typeahead form-control input-md" id="typeahead-clients"> 
</span> 

<select id="client_id" name="client_id" class="form-control input-md combobox" required=""> 
    <option value="59">fname lname 561280</option> 
..... shortened ..... 
    <option value="73">fname lname 561280</option> 
</select> 

所以我有2個問題:

  1. 的預輸入不起作用,因爲JSON是一個數組的數組,我怎麼可以設置此向上,以便在預輸入使用搜索的「標籤」和ID在選擇匹配選項值框?

  2. 一旦用戶做出選擇,我怎樣才能讓鍵入自動選擇選擇框中的匹配選項?

我只是這樣做的後備,如果用戶瀏覽器有問題的JavaScript,他們仍然可以使用下拉。 - 如果有更好的[更清潔]的方式來做到這一點,請提出建議。

回答

相關問題