【问题标题】:Bootstrap 4 tags input - Add tags only from the predefined listBootstrap 4 标签输入 - 仅从预定义列表中添加标签
【发布时间】:2019-02-26 12:10:00
【问题描述】:

我正在使用Bootstrap 4Bootstrap Tags Input 进行多类别选择选项。我想predefined_list中列出的预定义类别中选择多个项目@

现在,只要用户在输入字段中输入内容,自动建议就会起作用(使用预定义列表),用户可以看到建议的相关类别标签并添加它们。

但是,用户也可以通过手动输入来添加新的/自定义的任意类别标签。比如说,用户输入了“Apple”或“Banana”。类别列表也与自定义项目一起提交。我希望限制用户添加新/自定义类别,并且只能从现有的自动建议类别中进行选择。

<div class="col-lg-12">
    <span class="pf-title">Categories</span>              
    <div class="pf-field no-margin">
        <input id="category-input" name="category" type="text" data-role="tagsinput">
    </div>
</div>

<script type="text/javascript">
    var predefined_list = ["Linux", "Mac", "Windows"]
    $('#category-input').tagsInput({
    'autocomplete': {
    source: predefined_list
    },
    trimValue: true,
    });
</script>

【问题讨论】:

    标签: javascript jquery html bootstrap-4 bootstrap-tags-input


    【解决方案1】:

    只需在选项中添加freeInput: false

    类别
    <script type="text/javascript">
        var predefined_list = ["Linux", "Mac", "Windows"];
        $('#category-input').tagsInput({
            'autocomplete': {
                source: predefined_list
            },
            freeInput: false,
            trimValue: true,
        });
    </script>
    

    【讨论】:

      【解决方案2】:

      查看示例中的事件监听器 https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/

      ES6:

      $('#category-input').on('beforeItemAdd', (event) => {
        if(!predefined_list.includes(event.item)) {
           event.cancel = true;
        }
      });
      

      ES5:

      $('#category-input').on('beforeItemAdd', function(event) {
        if(predefined_list.indexOf(event.item) === -1) {
           event.cancel = true;
        }
      });
      
      1. 启动事件监听器来捕获事件“在添加项目之前”
      2. 如果predefined_list 不包括添加的项目,请将取消variable 设置为true,这样它就不会被添加
      3. 从 ES6 开始存在。 ES5 使用 indexOf(如果没有匹配则返回 -1)

      【讨论】:

        【解决方案3】:

        $('input').tagsinput('add', 'Linux', 'Mac', 'Windows');

        $('input').tagsinput('remove', 'Linux', 'Mac');

        $('input').tagsinput('removeAll');

        【讨论】:

        • 写代码来分享解决方案是可以的,但你也应该在详细的代码中添加描述。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-02
        • 1970-01-01
        • 1970-01-01
        • 2015-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多