我使用的是 typeahead.js 与 0.9.3,并使用 local
填充数据集
。
我将函数绑定(bind)到 typeahead:selected
和 typeahead:autocompleted
事件,以便我可以使用所选 typeahead 中的信息填充表单中的其他一些隐藏输入字段数据。
<form id="customer-form" action="/customer-form" method="post">
<input type="text" name="customer-typeahead" placeholder="Customer name" id="customer-typeahead"/>
<input type="hidden" name="customer-id" id="customer-id"/>
<input type="hidden" name="customer-name" id="customer-name"/>
</form>
页面上还有一些 HTML 框,我希望这些框中的信息能够填充预先输入以及隐藏的输入字段。换句话说,对于下面的 html,如果用户单击 .copy-data
div
,则 #customer-typeahead
和 #customer-name
应使用单击的 .customer-name
div
和 #customer-id
中的文本进行填充应使用单击的 .customer-id
div
中的文本进行填充。
<div class="copy-data">
<div class="buffer-div">
<div class="customer-id">1</div>
<div class="customer-name">Andrew</div>
</div>
</div>
<div class="copy-data">
<div class="buffer-div">
<p class="customer-id">2</p>
<p class="customer-name">Bryan</p>
</div>
</div>
<div class="copy-data">
<div class="buffer-div">
<div class="customer-id">3</div>
<div class="customer-name">Cathy</div>
</div>
</div>
我的大部分工作都使用以下 jquery:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="../js/typeahead.min.js" type="text/javascript"></script>
<script src="../js/hogan.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
var typeahead_template = [
'<div style="width: 190px; float:left;">{{value}}</div>',
'<div style="float:right;">{{id}}</div>'
].join('')
function changeTypeahead(obj, datum) {
$('input#customer-id').val(datum.id);
$('input#customer-name').val(datum.value);
};
$('#customer-typeahead').typeahead({
local: [{"value": "Andrew", "id": "1"}, {"value": "Bryan", "id": "2"}, {"value": "Cathy", "id": "3"} ],
limit: 5,
template: typeahead_template,
engine: Hogan
}).bind('typeahead:selected', function(obj, datum) {
changeTypeahead(obj, datum);
}).bind('typeahead:autocompleted', function(obj, datum) {
changeTypeahead(obj, datum);
});
$(".copy-data").click(function(){
id = $(this).find(".customer-id").text();
name = $(this).find(".customer-name").text();
$("#customer-typeahead").typeahead('setQuery', name)
$("#customer-typeahead").trigger('selected');
});
});
</script>
当用户单击 .copy-data
div
时,相应的客户名称
会填充输入文本框,但不会填充隐藏的输入。我打算以某种方式触发 typeahead:selected
事件,该事件会将适当的datum
传递给 changeTypeahead
函数,但这似乎并不即将发生。
有没有办法以这种方式利用预输入及其数据集的 native 功能,或者我必须直接设置隐藏输入?
更新:为了澄清,我想象使用 setQuery
会导致 typeahead 自行“触发”,即匹配查询,自行从数据集中确定适当的数据,然后触发所有适当的事件。如果可以避免,我宁愿不必从预输入数据集外部重新创建整个数据对象
最佳答案
您似乎忘记将数据
作为第二个参数传递给您的selected
触发器。尝试这样的事情:
$("#customer-typeahead").trigger('selected', {"id": id, "value": value});
关于javascript - 在 typeahead.js 中触发 "selected"事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22183320/