我希望我能解释一下我要做的事......
我使用twitter typeahead.js来显示蔬菜列表 . 用户开始键入蔬菜的名称,然后可以从列表中选择一个蔬菜,当选择该蔬菜时,填充输入 . 然后用户单击“添加项目”按钮 . 单击此按钮时,我想将输入的值添加到div(构建项目列表) .
我遇到问题,因为$(' . typeahead') . typeahead('val')方法似乎根本不起作用(错误:未定义) . 尝试$(' . 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>');
}
谢谢,
担
3 回答
这对我有用:
担,
也许您可以使用
typeahead:selected
事件并临时存储选定的数据 .然后,当需要使用数据时(在div输入交换中),您可以调用现有存储(
selectedDatum
) . 当输入值更新时,您可能需要在清除此商店时添加一些逻辑,但这应该相当容易(使用typeahead:opened
,keyup
等的某种组合 .希望这可以帮助 .
从我观察到的时候,当我们关注应用了typeahead的inputBox然后$(' . typeahead') . typeahead('val')工作 .
但是如果情况下焦点仍然在输入框中,让我们说一个人在onchange或oninput上做一些事情,然后在输入框中获取值,我们需要$(' . typeahead') . val();