2014-03-03 77 views
3

我想實現的功能是,如果我點擊一個DOM元素,那麼它應該自動填充一個帶有指定值的typeahead,它應該觸發typeahead:selectedTwitter Typeahead以編程方式選擇並觸發選擇

我發現與此相關的種種疑問和答案是jQuery#typeahead('val', val)jQuery#typeahead('setQuery', myQuery)

但兩人都只能選擇我想要的選項,它沒有觸發下拉選項點擊。有沒有辦法做到這一點?

回答

0

你應該叫change事件應用新值

$('.typeahead').val(Your value).trigger('change'); 
+0

請解釋一下你的解決方案一點點,在代碼塊包裹。 – Incognito

3

要觸發它就像如果用戶已經做出關於該項目的點擊,你必須更新你的數據在字段中的值。

簡短的回答是像謝爾蓋Stativa發佈:$('.typeahead').val(yourValue).trigger('change');

長的答案用的情況下使用的例子是在這裏,和我添加使用警犬一個sollution,但你的問題的核心不是這個複雜,我只希望它可以幫助未來的人,所以它就在這裏。

讓我們假設你有一個這樣的模板:

var arrNames = ['Luke','Han','Leia']; 

var nameDisplayBh = new Bloodhound({ 
     datumTokenizer: function (datum) { 
      return Bloodhound.tokenizers.whitespace(datum.RebelNames); 
     }, 
     queryTokenizer: Bloodhound.tokenizers.whitespace, 
     local: arrNames 
    }); 


    $('.typeahead').typeahead({ 
     hint: true, 
     highlight: true, 
     minLength: 1 
    },{ 
     name: Names Display, 
     source: nameDisplayBh.ttAdapter(), 
     display:"RebelNames", 
     templates: 
     { 
      suggestion: function(data) 
      { 
       return "<div>data.name</div>"; 
      } 
     } 
    }); 


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


var nameInYourList = arrNames[0]; 
$('.typeahead').val(nameInYourList).trigger('change'); 
相關問題