【发布时间】:2014-03-04 21:21:49
【问题描述】:
我使用 typeahead.js 与 0.9.3 并使用 local 填充 dataset。
我正在将函数绑定到 typeahead:selected 和 typeahead:autocompleted 事件,以便我可以使用所选预输入数据中的信息填充表单中的其他一些隐藏输入字段。
<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-iddiv中的文本填充。
<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-datadiv 时,相应的customer name 会填充输入文本框,而不是隐藏的输入。我打算以某种方式触发typeahead:selected 事件,这会将适当的datum 传递给changeTypeahead 函数,但这似乎没有发生。
有没有办法以这种方式利用预输入及其数据集的本机功能,还是我必须直接设置隐藏输入?
更新:为了澄清,我想象使用 setQuery 会导致 typeahead 自行“触发”,即匹配查询,自行从数据集中确定适当的数据,并触发所有适当的事件。如果可以避免的话,我宁愿不必在 typeahead 数据集外部重新创建整个基准对象
【问题讨论】:
标签: javascript jquery html typeahead.js typeahead