【问题标题】:Typeahead submit with enterTypeahead submit with enter
【发布时间】:2014-02-10 08:24:10
【问题描述】:

我正在使用 bootstrap typeahead,我想知道,如何在单击 enter 按钮时提交它?换句话说,如果我在预先输入的输入中输入“hello”并按下回车,我将如何提交“hello”?

我已经做到了,所以预输入不会自动选择第一个结果。

这是我的代码:

<form method="POST" action="script.php">
    <input name="typeahead_field" class="typeahead" data-provide="typeahead" autocomplete="off" type="text">
</form>

jQuery:

$('.typeahead').typeahead({
    items: 10,
    source: function (query, process) {
        $.ajax({
            url: 'typeahead.php',
            type: 'POST',
            dataType: 'JSON',
            data: 'query=' + query,
            success: function(data) {
                process(data);
            }
        });
    },
    highlighter: function(data) {

        // code that returns each result

        return html;
    },
    updater: function(data) {
        // code that redirects the user if they click the selection
    },
});

请帮忙!

【问题讨论】:

    标签: javascript jquery ajax twitter-bootstrap bootstrap-typeahead


    【解决方案1】:

    老问题,但值得回答。这是一个可能的解决方案:

    $('.typeahead').on('keydown', function(e) {
      if (e.keyCode == 13) {
        var ta = $(this).data('typeahead');
        var val = ta.$menu.find('.active').data('value');
        if (!val)
          $('#your-form').submit();
      }
    }
    

    编辑:第一次尝试非常天真:)

    【讨论】:

      【解决方案2】:

      您需要一个提交按钮才能在输入时启用提交。您可以使用此 CSS 隐藏按钮:

      <input type="submit" style="position: absolute; left: -9999px">
      

      (来自https://stackoverflow.com/a/477699/759971

      【讨论】:

        【解决方案3】:

        效果很好,但不像鼠标悬停事件那样突出显示选择。也许这个解决方案会更好,因为它似乎封装了先前答案的要点。 https://bwbecker.github.io/blog/2015/08/29/pain-with-twitter-typeahead-widget/

        【讨论】:

        • StackOverflow 通常更喜欢不仅仅是链接的答案(或只有一两句话的链接来推荐它)。
        猜你喜欢
        • 2015-07-02
        • 2013-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-17
        • 2021-06-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多