How to count the number of tags that exist in Bootstrap Tags Input field

998 views Asked by At

I'm building a CMS and I'd like to have my Bootstrap Tags Input require a minimum of 6 tags as well as count the number of tags and display it on a counter, like this:

<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 will hold the tags, and the span#tag-count will display the number of tags.

How do I do this with JavaScript or jQuery?

2

There are 2 answers

0
ikos23 On

From the docs, I'd say you can compute the count quite easily.

For instance using jQuery:

// both with return the count

$("#tags").val().split(",").length
// or
$("#tags").tagsinput('items').length

To update your count text, you can use:

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

if you ask about how count number of words in input text value you can convert it to array by spliting string by space skip empty elements(if you have more than one space beetwen words then its create empty element) and check length:

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