在typeahead.js中触发“selected”事件

时间:2014-03-04 21:21:49

标签: javascript jquery html typeahead.js typeahead

我正在使用typeahead.js与0.9.3并使用dataset填充local

我将函数绑定到typeahead:selectedtypeahead: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应填充所点击的文字{{ 1}} .customer-namediv应填充点击#customer-id .customer-id中的文字。

div

我的大部分工作都使用以下jquery:

<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>

当用户点击<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会填充输入文本框,但不会填充隐藏的输入。我打算以某种方式触发customer name事件,该事件会将相应的typeahead:selected传递给datum函数,但这似乎并没有发生。

有没有办法以这种方式利用typeahead及其数据集的本机功能,还是必须直接设置隐藏的输入?

更新:为了澄清,我想象使用changeTypeahead会导致输入&#34; fire&#34;单独地,即匹配查询,从数据集中自己确定适当的数据,并触发所有适当的事件。如果可以避免,我宁愿不必从typeahead数据集外部重建整个基准对象

1 个答案:

答案 0 :(得分:4)

您似乎忘记将datum作为第二个参数传递给selected触发器。尝试类似:

$("#customer-typeahead").trigger('selected', {"id": id, "value": value});

请参阅the documentation for jQuery.trigger