【问题标题】:How to display typeahead.js dropdown data on button click event?如何在按钮单击事件上显示 typeahead.js 下拉数据?
【发布时间】:2016-01-21 23:34:04
【问题描述】:

我正在尝试找到一种方法来利用 bootstrap-tagsinput 库和 Bootstrap-3-Typeahead 来创建具有组合框功能的标记输入字段。因此,用户可以在输入时看到可用的项目而无需获取它。

我刚刚开始创建它,到目前为止,我能够安全地运行 tags-inputtypeahead。所以现在它会在文本字段获得焦点时显示其所有数据。

后来我发现是通过触发它的focus函数来实现的。但我无法按照我尝试的方式触发它。

按钮点击事件发生后如何显示下拉列表?

这是我目前的代码:

<script>
$(document).ready(function() {  

    $('#device').tagsinput({
          typeahead: {
            source: ['Amsterdam', 'Washington', 'Sydney', 'Beijing', 'Cairo'],
            autoSelect: false,
            showHintOnFocus : true,
            minLength : 0
          }
    });

    $('#myButton').click(function() {
       $(".typeahead").trigger("focus");  // wont work
    });

});
</script> 

<div class="container">
<div class="bs-example">
    City : <input id="device" ></input>
    <button id="myButton" >Show</button>
</div>  
</div>

有什么建议吗?

【问题讨论】:

    标签: javascript jquery html css twitter-bootstrap


    【解决方案1】:

    您可以通过在隐藏的 &lt;input&gt; 元素上触发 keyup 来做到这一点:

    $('#device').tagsinput({
       typeahead: {
         source: ['Amsterdam', 'Washington', 'Sydney', 'Beijing', 'Cairo', 'Berlin', 'Stockholm', 'Copenhagen' ],
         autoSelect: false,
         minLength : 0
       }
    });     
    //trigger the typeahead
    $('#myButton').click(function() { 
       $(".bootstrap-tagsinput input").val('');
       $(".bootstrap-tagsinput input").trigger('keyup');
    });
    

    这里唯一的“但是”是:您必须在 typeahead 源中注释掉一行 [#408] 以防止它在鼠标悬停时关闭,因为 focusedshown 之间发生了不匹配。欺骗了预输入打开:

    mouseleave: function (e) {
      this.mousedover = false;
      //if (!this.focused && this.shown) this.hide(); <-- line #408
    }
    

    演示 -> http://plnkr.co/edit/TU7HUS49mck7BMJhMd1B?p=preview


    通过可滚动菜单获得“无限”项目的技巧:

    .dropdown-menu {
        overflow-y : scroll;
        max-height: 250px !important;
    }
    

    在选项中

    items : 1000,
    

    http://plnkr.co/edit/7yDk829M3wavyn1oJoAE?p=preview

    【讨论】:

    • 我设法通过将focus() 触发到标签输入添加的输入标签来做到这一点。 $("#id-of-the-input-added-by-tags-input").focus(); 不过你的建议值得一看。
    • 既然您对此很熟悉 :) 有没有办法避免下拉数据按照自然顺序进行排序?这里只显示有限数量的数据。如何在下拉列表中显示源中的所有数据。
    • @prime - 对答案进行了大量编辑,我实际上相信您会使用 typeahead.js,但您已经处于良好的旧 2.x typeahead 轨道上,没有点击问题中的链接: (
    • @prime,是的 - 和我在 plunkr 中的一样。
    【解决方案2】:

    $(".typeahead").focus(); 不工作吗?

    【讨论】:

    • 我设法通过将焦点()触发到由标签输入添加的输入标签来做到这一点。 $("#id-of-the-input-added-by-tags-input").focus();
    猜你喜欢
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多