简体   繁体   English

Bootstrap 4 标签输入 - 仅从预定义列表中添加标签

[英]Bootstrap 4 tags input - Add tags only from the predefined list

I'm usingBootstrap 4 , and Bootstrap Tags Input for making a multiple category selection option.我正在使用Bootstrap 4Bootstrap Tags Input来制作多类别选择选项。 I want to select multiple items only from the predefined categories listed in the predefined_list只想从列出的预定义的类别选择多个项目predefined_list

Right now, whenever user type something in the input field the auto suggestion works(using the predefined_list) and user can see suggested relevant category tag and, add them.现在,每当用户在输入字段中输入内容时,自动建议都会起作用(使用预定义列表),并且用户可以看到建议的相关类别标签并添加它们。

However, user can also add new/custom arbitrary category tags by manually typing it.但是,用户也可以通过手动输入来添加新的/自定义的任意类别标签。 Say, user typed 'Apple' or 'Banana'.比如说,用户输入了“Apple”或“Banana”。 The category list gets submitted with the custom items too.类别列表也与自定义项目一起提交。 I want user to be restricted from adding new/custom category and only select from the existing auto suggested category.我希望用户被限制添加新/自定义类别,并且只能从现有的自动建议类别中进行选择。

<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>

Just add freeInput: false in the options只需在选项中添加freeInput: false

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

Have a look at the Eventlisteners in the examples https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/查看示例中的 Eventlisteners https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/

ES6: ES6:

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

ES5: ES5:

$('#category-input').on('beforeItemAdd', function(event) {
  if(predefined_list.indexOf(event.item) === -1) {
     event.cancel = true;
  }
});
  1. Start Eventlistener which catches the event "before item gets added"启动事件侦听器,它在“添加项目之前”捕获事件
  2. If predefined_list doesn't include the item added set the cancel variable to true so it doesn't get added如果predefined_list 不包含添加的项目,则将cancel variable设置为true这样它就不会被添加
  3. Exists since ES6.从 ES6 开始存在。 ES5 works with indexOf (which returns -1 if there is no match) ES5 与 indexOf 一起使用(如果没有匹配则返回 -1)

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM