AllsWeb Blog
No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
Support
Knowledgebase
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
No Result
View All Result
AllsWeb White Logo
No Result
View All Result
Home JavaScript jQuery & AJAX

Autocomplete Textbox with Multiple Selection using jQuery in PHP

Autocomplete Textbox with Multiple Selection using jQuery in PHP

Lakshika Mathur by Lakshika Mathur
December 29, 2019
Reading Time: 5 mins read
0
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.

RELATED POSTS

Like Dislike Rating System with jQuery, Ajax, and PHP

Star Rating System with jQuery, Ajax, PHP, and MySQL

Form Validation using jQuery Validation Plugin

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.

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

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.

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

  • minChars – Specify the minimum number of characters the user must enter before a search is performed.
  • tokenLimit – Specify the maximum number of results.
<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.

  • Specify the HTTP method in the method attribute.
  • Specify the file path of the server-side in the 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>

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

  • When you submit the form, you can post the costs of the autocomplete multi-select textbox 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);
}

?>

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

Tags: Autocomplete TextboxMultiple Selection
ShareTweetSendShareSharePinScan
Lakshika Mathur

Lakshika Mathur

Related Posts

Like Dislike Rating System with jQuery, Ajax, and PHP
jQuery & AJAX

Like Dislike Rating System with jQuery, Ajax, and PHP

January 6, 2020
739
Star Rating System with jQuery, Ajax, PHP, and MySQL
jQuery & AJAX

Star Rating System with jQuery, Ajax, PHP, and MySQL

January 6, 2020
162
Form Validation using jQuery Validation Plugin
jQuery & AJAX

Form Validation using jQuery Validation Plugin

January 2, 2020
34
Display Loading Image While Page Loads using jQuery and CSS
HTML & CSS

Display Loading Image While Page Loads using jQuery and CSS

January 1, 2020
42
jQuery UI Autocomplete with Images and Custom HTML in PHP
HTML & CSS

jQuery UI Autocomplete with Images and Custom HTML in PHP

December 29, 2019
112
Auto Resize Textarea Height using jQuery
jQuery & AJAX

Auto Resize Textarea Height using jQuery

December 28, 2019
17
Next Post
Accessing Webcam and Capture Image using HTML5 and JavaScript

Accessing Webcam and Capture Image using HTML5 and JavaScript

One Time Temporary Download Link with Expiration in PHP

One Time Temporary Download Link with Expiration in PHP

Leave a Reply Cancel reply

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

Categories

  • Comparison (3)
  • HTML & CSS (9)
  • Interesting Facts (1)
  • JavaScript (27)
    • jQuery & AJAX (18)
  • PHP and MySQL (48)
  • Security (10)
  • SEO (2)
  • Trademark (2)
  • Tutorials (5)
  • Uncategorized (1)
  • Web Hosting (19)
    • VPS Server (5)
  • WordPress (8)

Recent Posts

  • Is the Trademark valuable to your Brand or domain?
  • Ideas For Ten Fantastic Online Business From Home
  • Some best free WordPress Themes for Affiliate Marketing Websites
  • Home
  • Posts
  • Privacy Policy
  • Terms and Conditions

Built and Maintained With ♥ by AllsWeb Team

No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison

Built and Maintained With ♥ by AllsWeb Team

Go to mobile version