Tags are a way to group and organize content. For example, in WordPress, it provides tags as an inbuilt taxonomy to group the content. In this tutorial, we are going to see how to add tags using “Bootstrap Tags Input” plugin.
This is a jQuery plugin that provides Bootstrap UI to add tags using a form input field.
This example has an HTML form with an input field. I initialize the ‘Tags Input’ library function with this field by using its id. While adding tags, it shows autocomplete suggestions by using Bloodhound engine.
It uses countries data stored in a JSON file and shows the autocomplete suggestion while typing data into the input field.
The following screenshot shows the Bootstrap form interface with the input field for adding tags with autocomplete. Download Bootstrap Tags Input and typeahead plugin file and add as a dependency to run this example.
The following code shows the jQuery script used to initialize the “Bootstrap Tags Input” plugin function. This is used to make an HTML form input field to add tags. I refer the input field id for the initialization.
I have used “Bootstrap typeaheadjs” to provide autocomplete suggestion while adding tags. I supply a JSON file for content to the typeahead engine to fetch the countries data.
Using this Tags plugin, we can add tags from the existing JSON data and also our own tags that are not listed in the autocomplete suggestion.
<input type="text" value="" id="tags-input" data-role="tagsinput" />
<script>
var countries = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'countries.json',
filter: function(list) {
return $.map(list, function(name) {
return { name: name }; });
}
}
});
countries.initialize();
$('#tags-input').tagsinput({
typeaheadjs: {
name: 'countries',
displayKey: 'name',
valueKey: 'name',
source: countries.ttAdapter()
}
});
</script>