Autocomplete Textbox with Multiple Selection using jQuery in PHP

Autocomplete Textbox with Multiple Selection using jQuery in PHP

Autocomplete Textbox with Multiple Selection using jQuery in PHP

Autocomplete Textbox shows the suggestions under the input field to permit the user to select a value from the pre-populated values list. Therefore, it is beneficial for the user to find and choose a desired amount from the auto-populated suggestions. If a user types in a textbox, the corresponding data is obtained from the database and shows recommendations in the dropdown under the textbox. You can make the text input field user-friendly by adding an autocomplete feature textbox using jQuery UI Autocomplete plugin in PHP.

Typically, the autocomplete input field permits you to select one value from the auto-suggestions list. But if you want to select more then one amount, then you need to implement the multi-select option in the autocomplete textbox. With the help of the following tutorial, we will explain to you how to add an autocomplete textbox and permit the user to select multiple items from the predefined dynamic list using jQuery with PHP and MySQL.

In the example script, we will create an autocomplete input field to search for skills.

Create Database Table

You have to create a table in the database. So, you can store the autosuggestions data. The following SQL will make 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` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
 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 you can attach the autocomplete feature.

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

jQuery Tokeninput Plugin:

Use the jQuery Tokeninput plugin to add the autocomplete feature to the input field. Firstly, 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 the input field using tokenInput()  method. Besides, specify the server-side script URL to fetch the data from the database.

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

Obtain the Autocomplete Data with MySQL and PHP (search.php)

There is a need for a server-side script to generate auto-suggest data based on the search request.  This search.php file creates search results and sends it to the tokenInput () method for the autocomplete list.

<?php

// Database configuration
$dbHost     = 'localhost';
$dbUsername = 'root';
$dbPassword = 'root';
$dbName     = 'allsweb';

// Connect with the database
$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'];

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

// Generate skills data array
$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 offers you a lot of configuration options to customize the autocomplete multiselect textbox. 

SEE ALSO: Create Short URL using PHP URL Shortener

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("search.php", {
        hintText: "Type your skills...",
        noResultsText: "Skill not found.",
        searchingText: "Searching..."
    });
});
</script>

Autocomplete Multiselect with Custom Delete Icon

You can use deleteText  option to specify a custom image for the delete link. If you want to hide the delete link, provide an empty string in deleteText.

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

Search and Token Limit in Autocomplete Multiselect

You can use minChars and tokenLimit to set the limit on search and token.

<script>
$(document).ready(function() {
    $("#skill_input").tokenInput("search.php", {
        minChars: 3,
        tokenLimit: 2
    });
});
</script>

Modify Response in Autocomplete Multiselect

Use the onResult callback function to return a response from the server before it is shown to the user.

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

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

SEE ALSO: jQuery UI Autocomplete with Images and Custom HTML in PHP

Get Selected Value from Autocomplete Multiselect

So, let’s check how to get the selected multiple values from the Autocomplete Multiselect textbox in PHP.

Initially, make an HTML form and place the autocomplete input field into it.

<form method="post" action="submit.php">
    <input type="text" name="skill_input" id="skill_input"/>
    <input type="submit" name="submit" value="SUBMIT">
</form>

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

<?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);
}

?>

Also, read our previous blog- Verify Email Address and Check if Email is Real using PHP

Exit mobile version