![](/img/trans.png)
[英]How to store tags from Bootstrap Tags Input field into my collection…?
[英]How to count the number of tags that exist in Bootstrap Tags Input field
我正在構建一個 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 執行此操作?
如果您詢問如何計算輸入文本值中的單詞數,您可以通過按空格拆分字符串來將其轉換為數組跳過空元素(如果您有多個空格甜菜單詞,則其創建空元素)並檢查長度:
const numOfWords = document.getElementById("tags").value
.split(" ").filter(word => !!word).length;
document.getElementById("tags-count").innerText = numOfWords;
從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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.