Tags Input with Autocomplete using jQuery and PHP
Published: 2023-04-20 17:34:13

Tags are used to organize posts or articles on the website. Tags provide an effective way to group related posts and make it easier for the user to find relevant posts quickly. It also helps readers to get a brief idea about the post without reading the entire content. Tags are more like categories, but they can describe posts in more detail than categories. Generally, one category is assigned to a post, on other hand you can use multiple tags for a single post.

The tags input field should be allowed to input multiple values separated by a specific separator. Mostly, the comma (,) is used as a separator for the multiple value’s input field. In this tutorial, we will show you how to create multiple tags input field using jQuery. You can build a user interface to manage tags with autocomplete feature using jQuery and PHP.

The example code will integrate a text field to input multiple tags. Also, an autocomplete feature will be provided to display tag suggestions from the database under the input field while the user starts typing.

Tags Input with jQuery
In this code sample, we will use the TagsInput jQuery plugin to convert a simple text input field to the tag list input area and allow the user to input multiple tag values.

The tag can be added by entering a comma (,).
The tag can be removed by a cross icon (x).
Define an HTML input field.

`<input type="text" id="tags_input">`
Include the jQuery and TagsInput library files.

`<!-- Include jQuery library -->
<script src="js/jquery.min.js"></script>

<!-- Include TagsInput jQuery library -->
<script src="js/jquery.tagsinput.js"></script>
<link rel="stylesheet" type="text/css" href="js/jquery.tagsinput.css" />`
Initialize the tagsInput plugin and specify the selector (#tags_input) to attach it to the input field.

`<script>
$('#tags_input').tagsInput();
</script>`
Tags Input with Autocomplete using PHP and MySQL
In the following example code snippet, we will show you how to add autocomplete feature to the tags input field using jQuery and PHP.

Create Database Table:
To store the autosuggestion tags data a table is required in the database. The following SQL creates a tags table with some basic fields in the MySQL database.

`CREATE TABLE `tags` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
HTML Input Element:
Create an input element with HTML.

<input type="text" id="tags_input">
jQuery Library:
jQuery library is required to use the TagsInput plugin.

<script src="js/jquery.min.js"></script>
jQuery UI Library:
To use autocomplete feature in tagsInput, the jQuery UI library is required. Include the jQuery UI library files first.

<link rel="stylesheet" href="js/jquery-ui/jquery-ui.min.css">
<script src="js/jquery-ui/jquery-ui.min.js"></script>
tagsInput Plugin:
Include the library files of the tagsInput jQuery plugin.

<script src="js/jquery.tagsinput.js"></script>
<link rel="stylesheet" type="text/css" href="js/jquery.tagsinput.css" />
Set server-side script URL in autocomplete_url option of the tagsInput() method.

<script>
$('#tags_input').tagsInput({
    'autocomplete_url': 'fetchData.php',
});
</script>`
Fetch Autocomplete Tags from Database with PHP and MySQL (`fetchData.php`):
The `fetchData.php` file is called by the `tagsInput()` method to retrieve the tags from the server-side script based on the search term.

Get the search term using the PHP $_GET method.
Fetch the matched records from the database with PHP and MySQL.
Return tags data as JSON encoded array using PHP `json_encode()` function.
`<?php 
 
// Database configuration 
$dbHost     = "localhost"; 
$dbUsername = "root"; 
$dbPassword = "root"; 
$dbName     = "codexworld"; 
 
// Create database connection 
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); 
 
// Check connection 
if ($db->connect_error) { 
    die("Connection failed: " . $db->connect_error); 
} 
 
// Get search term 
$searchTerm = $_GET['term']; 
 
// Fetch matched data from the database 
$query = $db->query("SELECT * FROM tags WHERE name LIKE '%".$searchTerm."%' AND status = 1 ORDER BY name ASC"); 
 
// Generate array with tags data 
$tagsData = array(); 
if($query->num_rows > 0){ 
    while($row = $query->fetch_assoc()){ 
        $data['id'] = $row['id']; 
        $data['value'] = $row['name']; 
        array_push($tagsData, $data); 
    } 
} 
 
// Return results as json encoded array 
echo json_encode($tagsData); 
 
?>`
tagsInput Options
Various configuration options are available to customize the tagsInput() functionality. Some useful options are given below.

autocomplete_url – URL to fetch the autocomplete data
autocomplete – Options and values for autocomplete data `({option: value, option: value})`
height – Height of the tags input area (100px)
width – Width of the tags input area (300px)
defaultText – Placeholder text for the input field (add a tag)
onAddTag – A callback function that triggers when the tag is added
onRemoveTag – A callback function that triggers when the tag is removed
onChange – A callback function that triggers when the tag value is changed
delimiter – Separator for a new tag ([‘,’,’;’] or a string with a single delimiter. Ex: ‘;’)
removeWithBackspace – Remove tag by backspace (true)
minChars – Minimum character limit (default, 0)
maxChars – Maximum character limit (default, no limit)
placeholderColor – Placeholder text color (default, #666666)
Get Value of Input Tags with PHP
Once the form is submitted, you can get the value of the tags input field using the $_POST method in PHP. The following example code snippet shows how to submit the form and get the tags input field’s value using PHP.

HTML Form with Tags Input:

`<form method="post" action="submit.php">
    <!-- Input field -->
    <div class="form-group">
        <label>Tags:</label>
        <input type="text" id="tags_input" name="tags_input">
    </div>

    <!-- Submit button -->
    <input type="submit" name="submit" value="Submit">
</form>`
Get Value of Tags Input:
After the form submission, use the $_POST method in PHP to retrieve the value from the tags input field.

`if(isset($_POST['submit'])){ 
    $tags = $_POST['tags_input']; 
 
    echo '<p><b>Selected Tags:</b></p> '.str_replace(',', '<br/>', $tags); 
}`
Autocomplete Textbox with jQuery UI using PHP and MySQL

**Conclusion**
Tags input with autocomplete feature is very useful for the tags management in post/product creation form. You can the example code to allow the user to input multiple tags and manage them easily. The autocomplete functionality helps to find relevant tags quickly and select from the pre-populated list. You can also get multiple values from the input fields and insert tags in the database with PHP and MySQL.