【问题标题】:How to count the number of tags that exist in Bootstrap Tags Input field如何计算 Bootstrap 标签输入字段中存在的标签数量
【发布时间】:2020-10-18 01:32:12
【问题描述】:

我正在构建一个 CMS,我想让我的 Bootstrap 标签输入至少需要 6 个标签,并计算标签的数量并将其显示在计数器上,如下所示:

<input type="text" data-role="tagsinput" placeholder="Add some tags!" id="tags" required>
<label for="tags">You must enter at least 6 tags. You have added <span id="tag-count">0</span> tags.</label>

input#tags 将保存标签,span#tag-count 将显示标签数量。

如何使用 JavaScript 或 jQuery 做到这一点?

【问题讨论】:

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


【解决方案1】:

如果您询问如何计算输入文本值中的单词数,您可以通过按空格分割字符串跳过空元素(如果您有多个空格 beetwen 单词则创建空元素)并将其转换为数组并检查长度:

const numOfWords = document.getElementById("tags").value
                  .split(" ").filter(word => !!word).length;
document.getElementById("tags-count").innerText = numOfWords; 

【讨论】:

    【解决方案2】:

    来自the docs,我想说你可以很容易地计算出计数。

    例如使用 jQuery:

    // both with return the count
    
    $("#tags").val().split(",").length
    // or
    $("#tags").tagsinput('items').length
    

    要更新计数文本,您可以使用:

    $('#tags').on('itemAdded', function(event) {
      const count = $("#tags").val().split(",").length;
      $('#tag-count').text(count);
    });
    

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 2011-10-14
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 2021-08-21
      • 2016-11-14
      相关资源
      最近更新 更多