Tags using Bootstrap Tags Input Plugin with Autocomplete

by Vincy. Last modified on July 5th, 2023.

Tags are a way to group and organize content. For example, WordPress provides tags as an inbuilt taxonomy to group the content. This tutorial will show how to add tags using the “Bootstrap Tags Input” plugin.

This jQuery plugin 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 using its id. While adding tags, it shows you autocomplete suggestions by using the Bloodhound engine.

View Demo

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 it as a dependency to run this example.

bootstrap-tags-input-output

Bootstrap Tags Input initialization using jQuery

The following code shows the jQuery script initializing the “Bootstrap Tags Input” plugin function. This is used to make an HTML form input field to add tags. I refer to the input field id for the initialization.

I have used “Bootstrap typeaheadjs” to provide autocomplete suggestions 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 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>

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “Tags using Bootstrap Tags Input Plugin with Autocomplete”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page