我希望我能解释我想要做什么...typeahead.js获取按钮单击的输入值
我正在使用twitter typeahead.js显示蔬菜列表。用户开始输入蔬菜的名称,然后可以从列表中选择一种蔬菜,当选择蔬菜时,填充输入。用户然后点击一个按钮“添加项目”。单击此按钮时,我想将输入的值添加到div(构建项目列表)。 ('。typeahead')。typeahead('val')方法似乎根本没有工作(错误:undefined)。尝试$('。typeahead')。val()返回一个空字符串。
如何在按下按钮时获取输入值?
//the url produce/get_produce_items returns an array of vegetables. The filter organises these into value (the vegetable name) and id (the id of the vegetable in the db)
var produce_items = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: site_url('produce/get_produce_items'),
filter: function(list) {
return $.map(list, function(produce_item) { return { value: produce_item.name,id: produce_item.id }; });
},
ttl:10000
}
});
produce_items.initialize();
var typeaheadSettings = {
hint: true,
highlight: true,
minLength: 1,
};
var typeAheadDataset = {
name: 'produce_items',
displayKey: 'value',
valueKey: 'value',
source: produce_items.ttAdapter(),
};
$('#items_list .typeahead').typeahead(typeaheadSettings,typeAheadDataset);
//here's the button that is clicked, and when clicked should replace the typeahead with a div containing the typeahead value
$('#add_donation_item_line_btn').click(function() {
var item_count = $('input[name=item_count]');
var count = item_count.val();
var nextCount = parseInt(count) + 1;
//firm the line (swap the input out for a div)
var val = $('#items_list > div#don_line_'+count+' .typeahead').val();
firmLine(count,val);
$('#items_list .typeahead').trigger('added');
item_count.val(nextCount);
});
$('#items_list .typeahead').on('added',function(val){
$('#items_list .typeahead').typeahead(typeaheadSettings,typeAheadDataset);
});
$('#items_list .typeahead').on('typeahead:selected',function(evt, item){
$(this).parent('span').parent('div').find('input[type=hidden]').val(item.id);
});
function firmLine(count,val) {
var line = $('#items_list > div#don_line_'+count+' .typeahead');
line.typeahead('destroy');
line.replaceWith('<div class="span2 typeahead-replacement">'+val+'</div>');
}
感谢,
丹
谢谢@tbloncar。关于这个话题也在这里讨论:https://github.com/twitter/typeahead.js/issues/193 –