1

我正在使用typeahead.js将产品 ID 分配给隐藏的 html 表单字段。当有比赛时,这很有效:

$('.products_tt .typeahead').typeahead
    name: 'products_tt',
    prefetch: 
        url: '/products.json',
        ttl: 60 * 5e3
    template: '<p><strong>{{value}}</strong> – {{year}}</p>',
    engine: Hogan

$('.products_tt .typeahead').on "typeahead:selected typeahead:autocompleted", (e,datum) ->
    $('#disk_file_product_id').val(datum.id)

当输入字段留空时,我清除隐藏字段:

$('.products_tt .typeahead').blur ->
    if $(this).val().length == 0
        $('#disk_file_product_id').val("")

但是,当在输入字段中输入文本但没有匹配项时,我还需要清除隐藏字段。

我的 Java/Coffeescript 技能很弱,所以不知道该怎么做?!?

4

2 回答 2

5

以下其中一项应该有效:

1)首先挂钩输入字段的change事件,并#disk_file_product_id在那里清除。如果有选择,您的typeahead事件稍后将再次设置。这也可以保存您的blur回调。

$('.products_tt .typeahead').change ->
    $('#disk_file_product_id').val("")

#disk_file_product_id2)在opened和事件中清除closed,而不是在字段的change事件中。我不喜欢这个。

$('.products_tt .typeahead').on "typeahead:opened typeahead:closed" ->
    $('#disk_file_product_id').val("")
于 2013-08-04T06:47:10.923 回答
2

我知道这已经几个月了,但这是你可以做到的:

使用 jQuery 查看每个 keyup 事件的 DOM 中有多少“.tt-suggestions”。如果没有,请清除隐藏字段。

$('.products_tt .typeahead').typeahead({
    name: 'products_tt',
    prefetch: url: '/products.json',
    ttl: 60 * 5e3
    template: '<p><strong>{{value}}</strong> – {{year}}</p>',
    engine: Hogan
}).on("typeahead:selected typeahead:autocompleted", function (e, datum) {
    $('#disk_file_product_id').val(datum.id);
}).on('keyup', function () {
    if($('.tt-suggestion').length === 0){
        $('#disk_file_product_id').val("");
    }
});
于 2014-01-07T02:20:21.917 回答