在Bootstrap的typeahead()自动完成中如何提交选择?

19

1
如果你还在寻找,我创建了一个扩展程序来增加Typeahead插件的一些功能,就像你所询问的那样。https://github.com/tcrosen/Bootstrap-Typeahead-Extension - Terry
6个回答

22

有一种干净的方法使用 updater 回调函数:

input.typeahead({
    'source' : ['foo', 'bar'],
    'updater' : function(item) {
        this.$element[0].value = item;
        this.$element[0].form.submit();
        return item;
    }
});

当用户选择一个选项(通过鼠标单击或键盘),回调函数会填充输入框并发送表单。

字段已被选中(并填充),但表单未被提交。$('#search-box.typeahead').typeahead({ hint: true, highlight: true, minLength: 1 }, { name: 'states', displayKey: 'value', source: substringMatcher(states), updater:function(item){ this.$element [0] .value = item; this.$element [0] .form.submit(); 返回项目; } }); - TheTechGuy

11
如果您使用外部typeahead.js插件(推荐用于Bootstrap 3):
只需使用自定义事件来触发选择的表单即可。
$('#my-input')
   .typeahead({/* put you options here */})
   .on('typeahead:selected', function(e){
     e.target.form.submit();
   });

有关自定义事件的更多信息,请参见此处,有关JSfiddle演示的内容。


拯救了我的生命 @HaNdTriX - Kathan
我很高兴听到这个消息。 :-) - HaNdTriX

7

可能不是最好的解决方案,但我在本地尝试了一下,它可以工作。

如果你的typeahead看起来像这样...

    <form id="test-form" method="post" action="">
            <input id="test-input" type="text" data-provide="typeahead" 
             data-source='["1","2',"3"]' />
    </form>

然后,您可以使用此JavaScript提交它。
   <script type="text/javascript">
       $('#test-input').change(function() {
          $('#test-form').submit();
       });
   </script>  

2
嗯,我刚试了一下。似乎只有在直接选择选项时才有效,但是当我按回车键或使用Tab键进行选择时无效。 - Nathan Waters

3

是的,我明白这不是最好的解决方案。但这是我能想到的唯一的临时解决办法。 - Jako

0
为了从typeahead数据选择中填充HTML表单中隐藏字段的值,我执行了以下操作:
$('#prefetch').typeahead({
 hint: true,
 highlight: true,
 minLength: 1
},
{
 name: 'trees',
 source: trees,
 limit: 15 
}).on('typeahead:selected', function(e) {
 var result = $('#prefetch').val()
 $('#formpane input[name=\"myID\"]').val(result)
});

供参考,这是HTML代码:

<body>
 <div id="formpane">
  <form action="/thanks" method="POST">
    <input class="typeahead" type="text" placeholder="select categories" id="prefetch">
    <button type="submit">Submit</button>
    <input type="hidden" name="myID" />
  </form>
 </div>
<script type="text/javascript" src="js_file_above.js"></script>
</body>

0
我在输入框上添加了一个“blur”回调函数。请注意,您需要等待一段时间,因为typeahead可能会更改输入框中的值,并且在此之前不会调用“blur”回调函数。这只是一个解决方法,但它有效。
$('input.myTypeaheadInput').blur(function(e) {
    window.setTimeout(function() {
        window.console && console.log('Works with clicking on li item and navigating with the keyboard. Yay!');
    }, 50);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接