【问题标题】:Select first suggestion from Typeahead.js when hit Enter key in the field在字段中按 Enter 键时从 Typeahead.js 中选择第一个建议
【发布时间】:2014-11-06 16:59:38
【问题描述】:

当我专注于该字段时按 Enter 键时,我想从 Typeahead.js 建议项中选择第一个可用建议。

我现在得到了这个代码:

$('#cities-prefetch .typeahead').on('keyup', function(e) {
    if(e.which == 13) {
        var value = $('input:text#city').typeahead('val');
    }
});

但这只会从字段本身中获取当前选定的值。

请帮忙!

【问题讨论】:

标签: jquery twitter-bootstrap-3 typeahead.js


【解决方案1】:

如果按下 Enter 键,您可以在第一个建议上触发 click

$('#cities-prefetch .typeahead').on('keyup', function(e) {
    if(e.which == 13) {
        $(".tt-suggestion:first-child", this).trigger('click');
    }
});

看到这个Demo

【讨论】:

  • 现在是 .twitter-typeahead 而不是 .typeahead。对于那些需要使用它的人。
  • 如果您的预输入在表单内,它会提交表单而不是执行 keyup 事件。我的解决方案是触发点击表单提交。
  • 这对我不起作用。它只是跳到下一个输入
  • 我不得不在页面上方使用一个类/id 来调用 keyup 函数。我使用了 Bootstrap .row 类 - $('.row').on('keyup', function(e) {。可能会帮助某人..
【解决方案2】:

这在我的情况下有效。

$('[id$=_form]').on('keydown', '.twitter-typeahead #input_id', function(e) {
    if(e.which == 13) {
        e.preventDefault();
        $('.tt-selectable').first().click();
    }
});

【讨论】:

    【解决方案3】:

    在 typeahead.js 0.11.1 中,这似乎对我有用。

    $(element).on('keyup', function(e) {
        if(e.which == 13) {
            e.preventDefault();
            //find the selectable item under the input, if any:
            var selectables = $(element).siblings(".tt-menu").find(".tt-selectable");
            if (selectables.length > 0){
                 $(selectables[0]).trigger('click');    
            } 
        }
    });
    

    【讨论】:

      【解决方案4】:

      您可以使用autoselect - 如果true,当按下 Enter 键时,预输入将自动选择第一个建议。默认为falserefrence

      【讨论】:

      【解决方案5】:
      $(element).on('keyup', function(e) {
        if(e.which == 13) {
          e.preventDefault();
          var selectables = $(element).siblings(".tt-dropdown-menu").find(".tt-suggestion");
          if (selectables.length > 0) {
            $(selectables[0]).trigger('click');
          } else {
              $(butto_element).trigger('click');
          }
        }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多