Autocomplete Textbox with Multiple Selection using jQuery in PHP

Autocomplete Textbox displays the suggestions under the input field to allow the user to select a value from the pre-populated values list. It helps the user to find and select a desired value from the auto-populated suggestions. When the user typing in the textbox, the respective data is fetched from the database and shown the suggestions in the dropdown under the textbox. You can easily make the text input field user-friendly by adding autocomplete feature textbox using jQuery UI Autocomplete plugin in PHP.

Generally, the autocomplete input field allows selecting one value from the auto-suggestions list. But if you want to select multiple values, the multi-select option needs to be implemented in the autocomplete textbox. In this tutorial, we will show you how to add autocomplete textbox and allow the user to select multiple items from the dynamic predefined list using jQuery with PHP and MySQL.

In the example script, we will create a autocomplete input field to search skills data from the database.

  • HTML input field to search skills.
  • Fetch the matched skills from the server-side script while the user starts typing in the textbox.
  • List the dynamic values under the input field.
  • Allow multiple selections from the auto-suggestions dropdown.

Create Database Table

A table needs to be created in the database to store the auto-suggestions data. The following SQL creates a skills table in the MySQL database.

CREATE TABLE `skills` (
  `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;

Autocomplete Textbox with Multiple Selection

HTML Input Field:
Define an input element where autocomplete feature will be attached.

<input type="text" id="skill_input"/>

jQuery Tokeninput Plugin:
We will use the jQuery Tokeninput plugin to add autocomplete feature to the input field. At first, include the jQuery and Tokeninput library files.

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

<!-- Tokeninput plugin library -->
<script src="js/jquery.tokeninput.js"></script>
<link rel="stylesheet" href="css/token-input.css" />

Initialize and attach the Tokeninput to input field using tokenInput() method. Also, specify the server-side script URL to fetch the data from the database.

<script>
$(document).ready(function() {
    $("#skill_input").tokenInput("fetchData.php");
});
</script>

Fetch Autocomplete Data with PHP and MySQL (fetchData.php)

A server-side script needed to generate the auto-suggestions data based on the search request. This fetchData.php file generates the search results and sends to the tokenInput() method for the autocomplete list.

  • Connect to the MySQL database.
  • Get the search term with the GET parameter named q.
  • Fetch matched data from the database based on the search term using PHP and MySQL.
  • Generate an array of search results data.
  • Render the search results in JSON format.
<?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['q'];

// Fetch matched data from the database
$query $db->query("SELECT id, name FROM skills WHERE name LIKE '%".$searchTerm."%' AND status = 1 ORDER BY name ASC");

// Generate array with skills data
$skillData = array();
if(
$query->num_rows 0){
    while(
$row $query->fetch_assoc()){
        
$skillData[] = $row;
    }
}

// Return results as json encoded array
echo json_encode($skillData);

?>

The jQuery Tokeninput plugin provides various configuration options to customize the autocomplete multiselect textbox. Some of the most useful configuration options for multiple select autocomplete are given below.

Autocomplete Multiselect with Custom Labels

You can specify the custom labels for the hint, no result, and searching text.

<script>
$(document).ready(function() {
    $("#skill_input").tokenInput("fetchData.php", {
        hintText: "Type your skills...",
        noResultsText: "Skill not found.",
        searchingText: "Searching..."
    });
});
</script>

Autocomplete Multiselect with Custom Delete Icon

Use deleteText option to specify a custom image for delete link. If you wish to hide the delete link, provide an empty string in deleteText.

<script>
$(document).ready(function() {
    $("#skill_input").tokenInput("fetchData.php", {
        deleteText: "&#x2603;"
    });
});
</script>

Search and Token Limit in Autocomplete Multiselect

Use minChars and tokenLimit to set the limit on search and token.

  • minChars – Specify the minimum number of characters the user must enter before a search is performed.
  • tokenLimit – Specify the maximum number of results allowed to be selected by the user.
<script>
$(document).ready(function() {
    $("#skill_input").tokenInput("fetchData.php", {
        minChars: 3,
        tokenLimit: 2
    });
});
</script>

Modify Response in Autocomplete Multiselect

You can use onResult callback function to modify the response back from the server before shown to the user.

<script>
$(document).ready(function() {
    $("#skill_input").tokenInput("fetchData.php", {
        onResult: function(results){
            $.each(results, function (index, value) {
                value.name = "CODEX: " + value.name;
            });

            return results;
        }
    });
});
</script>

Get Selected Value from Autocomplete Multiselect

Now, we will show you how to get the selected multiple values from the Autocomplete Multiselect textbox in PHP.

At first, create an HTML form and place the autocomplete input field into it.

  • Specify the HTTP method in the method attribute.
  • Specify the file path of the server-side in action attribute.
  • Add a submit button to the form.
<form method="post" action="submit.php">
    <input type="text" name="skill_input" id="skill_input"/>
    <input type="submit" name="submit" value="SUBMIT">
</form>

In the server-side script (submit.php), use the PHP $_POST method to get the selected values.

  • When the form is submitted, the values of the autocomplete multi-select textbox is posted in this script.
  • You will get the IDs of the selected items as a comma (,) separated string.
  • Use the explode() in PHP to convert ids string to an array.
<?php

if(isset($_POST['submit'])){
    
// Get selected skills
    
$selected_skills_ids $_POST['skill_input'];
    
    
// Convert skills ids string to array
    
$selected_skills_arr explode(','$selected_skills_ids);
}

?>

Autocomplete Textbox with Multiple Values using jQuery, PHP and MySQL

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

Leave a reply

keyboard_double_arrow_up