JQuery:没有匹配的Twitter Typeahead函数

JQuery: Twitter Typeahead function for no match

本文关键字:Twitter Typeahead 函数 JQuery      更新时间:2023-09-26

我使用typeahead.js为隐藏的html表单字段分配产品id。这在比赛时非常有效:

$('.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/Coffeescapet技能很弱,所以不知道该怎么做?!?

以下其中一项应该有效:

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

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

2) 在openedclosed事件中清除#disk_file_product_id,而不是在字段的change事件中清除。我不太喜欢这个。

$('.products_tt .typeahead').on "typeahead:opened typeahead:closed" ->
    $('#disk_file_product_id').val("")

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

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

$('.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("");
    }
});