Typeahead提交输入

时间:2014-01-20 23:34:20

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

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

我已经这样做了,因为预先输入不会自动选择第一个结果。

这是我的代码:

<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
    },
});

请帮忙!

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

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

$('.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 :(得分:0)

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

相关问题