The Autocomplete textbox allows the user to quickly find and select a value from the pre-populated option list. It displays the suggestions automatically while the user types into the field. Using the jQuery UI Autocomplete plugin, you can easily add an autocomplete textbox on the website. The jQuery UI Autocomplete plugin converts the input field into an Autocomplete. When the user typing in the autocomplete input field, this plugin starts searching for matched values and lists them to choose from.
Autocomplete textbox provides a user-friendly way to add a search input field with auto-suggestions dropdown in the web application. It is very useful when you want to populate suggestions from the database when the user starts typing in the input field. In this tutorial, we will show you how to implement Autocomplete textbox and display suggestions from the database using jQuery, PHP, and MySQL.
The example code will implement an auto-suggestions input field for skills search. The autosuggestion options will be fetched from the database and listed under the textbox while the user starts typing in the textbox.
To store the autosuggestions data a table needs to be created in the database. The following SQL creates a skills
table with some basic fields 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;
The following code attaches a autocomplete suggestion box to the input field with the jQuery UI plugin.
jQuery UI Autocomplete Plugin:
Include the jQuery and jQuery UI library files to use the Autocomplete plugin.
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- jQuery UI library -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
Initialize Autocomplete:
The autocomplete()
function initialize the Autocomplete plugin.
#skill_input
) of the input field element where autocomplete feature will be attached.fetchData.php
) to retrieve the data for auto-suggestions.<script>
$(function() {
$("#skill_input").autocomplete({
source: "fetchData.php",
});
});
</script>
HTML Input Element:
Initially, an input text field is provided to enter the skills.
autocomplete()
method.<div class="form-group">
<label>Programming Language:</label>
<input type="text" id="skill_input" placeholder="Start typing...">
</div>
The fetchData.php
file is called by the autocomplete() method of Autocomplete plugin. This file retrieves the skills data based on the search term and returns data as a JSON encoded array using PHP and MySQL.
The autocomplete() method makes a GET request to the source URL and added a query string with a term field. So, you can get the search term using PHP GET method. The following PHP code, fetch the records from the MySQL database (skills table) and filter the records by $_GET['term']
. The filtered skill data returned to autocomplete() method as a JSON encoded array.
<?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 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()){
$data['id'] = $row['id'];
$data['value'] = $row['name'];
array_push($skillData, $data);
}
}
// Return results as json encoded array
echo json_encode($skillData);
?>
On form submission, the selected item value is sent to the server-side for autocomplete input field. If you want to get the ID of the selected value, you need to replace the input field value with item ID.
$(function() {
$("#skill_input").autocomplete({
source: "fetchData.php",
select: function( event, ui ) {
event.preventDefault();
$("#skill_input").val(ui.item.id);
}
});
});
Various configuration options are available to customize the jQuery UI Autocomplete plugin functionality. Some useful configuration options of the Autocomplete plugin are given below.
source
– Required. The source must be specified from where the data will be fetched for suggestions list. You can specify the local or remote source.
[ "Choice1", "Choice2" ]
OR [ { label: "Choice1", value: "value1" }, { label: "Choice2", value: "value2" }, ... ]
$( ".selector" ).autocomplete({ source: [ "PHP", "Python", "Ruby", "JavaScript", "MySQL", "Oracle" ] });
http://example.com
$( ".selector" ).autocomplete({ source: "http://example.com" });
minLength
– Optional (Default 1). The minimum number of characters that must type before the search is performed.
$( ".selector" ).autocomplete({ minLength: 5 });
select( event, ui )
– Triggered when a value is selected from the suggestions.
$( ".selector" ).autocomplete({ select: function( event, ui ) {} });
Once the form is submitted, you can get the value of the autocomplete input field using the $_POST
method in PHP. The following example code snippet shows how to submit the form and get the autocomplete field’s value using PHP.
1. HTML Form with Autocomplete Input:
<form method="post" action="submit.php">
<!-- Autocomplete input field -->
<div class="form-group">
<label>Programming Language:</label>
<input type="text" id="skill_input" name="skill_input" placeholder="Start typing...">
</div>
<!-- Submit button -->
<input type="submit" name="submit" value="Submit">
</form>
2. Get Value of Autocomplete Input:
After the submission, in form action script (submit.php), use the $_POST method in PHP to retrieve the value from the autocomplete input field.
<?php
if(isset($_POST['submit'])){
$skill = $_POST['skill_input'];
echo 'Selected Skill: '.$skill;
}
?>
jQuery UI Autocomplete with Images and Custom HTML in PHP
jQuery UI autocomplete input field is very useful for the search field where you want to list the term suggestions to help the user to enter the relative search keywords/terms. The jQuery UI Autocomplete plugin makes it easier to convert an HTML input field to autocomplete input. This example script allows the user to find relevant terms and select values from the pre-populated list for search/filter. You can use the selected value or ID from the autocomplete options list for server-side processing.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
How to make the form displayed to NAME and send the ID
Thank you very mutch. Very helpfull article for me. You just saved my life
THANK YOU SO MUCH BROS,
THIS IS SIMPLE AND WORK AS WELL!!!
Thank! This is very short, descriptive, helpful, you saved my life!!
i need code for automatic searc engine suggestion in php with mssql server
how can I make this work in wordpress? other question is: once you find the word you searching and press ENTER, how can I make it show other fields from the same DB row?
thank you very much.
this work. but i have one question: how to echo image field from database and display it.
help me understand. where does the search.php file come from?
thanks you it works
What is this , i can’t understand. anybody know that
//get search term
$searchTerm = $_GET[‘term’];
how to display “No matches found” message when no data is matching
How can I use this for Hindi text?
How do I change the style of the input and dropdown?
Very, very usefull script, but i have one question: how to pass the ‘id’ field from the same table to the PHP script and read it using $ _POST []?
To pass an additional parameter (id) in jQuery UI Autocomplete, checkout this tutorial – http://www.codexworld.com/how-to/pass-additional-parameters-in-jquery-ui-autocomplete/
Thank you, do you have this same in java?
Currently, we do not publish tutorials on Java.
Great article!
However I have a few suggestions as in my case the select statement was returning duplicate values:
1. in the “search.php” file, remove the ‘order by’ condition from the query and change:
echo json_encode($data);
to
echo json_encode(array_unique($data));
2. Please sanitize your SELECT statement by escaping characters to avoid SQL injection attacks.
Thanks for this code.
It is very useful …..
I have many input field that need same autocomplete procedure apply to. How can I do that ?
How to show autocomplete result in both input field as well in another DIV?
Thank you so much. This help me alot.
How can you make the autocomplete only start once the user has typed 5 characters, instead of on the first character?
@Jeremy Use minLength option like the below.
great article………
Hey,
Please don’t forget to escape the search term using bindValue 😉
Thank you very much.
When I include jQuery UI stylesheet to my existing project. my input fields lost the styles of its current theme. How can I Implement it without using JQ UI CSS.
thanks a million …
How we can put id of that select term? I want to pass further this id in a form? can you tell me? please ASAP?
@Arman To pass the additional parameters in jQuery UI Autocomplete see this guide – http://www.codexworld.com/how-to/pass-additional-parameters-in-jquery-ui-autocomplete/
Hi thank you so much this plugin works,
I have a question how to implement this plugin for dynamic text box that is if i append a new text box in table or form with the same idea this is not working.
So can you please tell me how to implement this for dynamic searches.
How to search [airportcode] in inputbox then use this Autocomplete show [airportcode or countryname] ?
Thank you.
Thank you so much.
Thank you very much, short and sweet above all it works 🙂
How to Add Multipl Skils Sepreted by coma on the same textbox
@Rakesh We’ve already published the tutorial on Autocomplete Textbox with Multiple Values. See it from here – http://www.codexworld.com/autocomplete-textbox-multiple-values-jquery-php-mysql/
It’s very usefull and easy solution.
thank you for that.
Works great! Thank you very much to share with us!
thanks you so much, this tutorial help me
Thanks Boss You are Great
eventhough i’m not learn about java, I still manage to use it.
thanks though 😀
Thanks so much.. this example is perfect… thanks for spend your time making this tutorial
Hello, thank you very much!!
And a question. How i get the skill id from the DB in another input ?
thank you very much;
this works best. short and descriptive . very helpful.