簡體   English   中英

Bootstrap 4 標簽輸入 - 僅從預定義列表中添加標簽

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

我正在使用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>

只需在選項中添加freeInput: false

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

查看示例中的 Eventlisteners 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 不包含添加的項目,則將cancel variable設置為true這樣它就不會被添加
  3. 從 ES6 開始存在。 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