The jQuery UI Autocomplete plugin offers you a quick way to add autocomplete suggestions feature to the textbox. It permits the user to search and select a value from a pre-populated list quickly. Therefore, when the user starts to type in the input field, the Autocomplete plugin fetches the matched values and lists them under the textbox. You can integrate the autocomplete textbox functionality using jQuery UI, PHP, and MySQL.
Typically, the autocomplete widget retrieves values from the database and displays the suggestions as a text format under the input field. However, you can customize the autocomplete dropdown and suggestion list with custom HTML code. The custom autocomplete dropdown list is helpful when you want to maintain the design with a webpage layout. In this tutorial, we will show you how to add custom HTML and display images and text in autocomplete using jQuery UI, PHP, and MySQL.
In the sample script, we will integrate an auto-suggestions textbox for members’ search, and display images and text in the autocomplete drop-down.
- Autocomplete textbox to search the members by name.
- When the user starts typing in the input field, fetch the matched members’ data from the database.
- There is a list of all the member’s data with name and image in the auto-suggestions dropdown.
Make a Database Table
To store the autosuggestions data, you need to create a table that needs to in the database. The following SQL creates a user table with some necessary fields in the MySQL database.
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `image` varchar(150) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `modified` datetime 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
JavaScript Code:
Add the jQuery and jQuery UI library files to use the Autocomplete plugin.
<!-- jQuery library --> <script src="jquery-ui/jquery/jquery.min.js"></script> <!-- jQueryUI library --> <link rel="stylesheet" href="jquery-ui/jquery-ui.css"> <script src="jquery-ui/jquery-ui.js"></script>
Use the autocomplete() method to adjust the jQuery UI Autocomplete plugin.
- source – Specify the path of the server-side script to fetch the dynamic data from the database.
- minLength – The minimum number of characters the user must type to perform the search
- select – This event is triggered when we select an item from the suggestions dropdown.
- On selecting an item, it will set the value to the autocomplete input field, and the user ID will be set to the hidden input field.
- _renderItem – The renderItem extension helps to customize the autocomplete widget.
- Define a custom class for each item of the auto-suggestions list.
- Render the images and text with custom HTML.
<script> $(document).ready(function(){ $("#searchInput").autocomplete({ source: "getUsers.php", minLength: 1, select: function(event, ui) { $("#searchInput").val(ui.item.value); $("#userID").val(ui.item.id); } }).data("ui-autocomplete")._renderItem = function( ul, item ) { return $( "<li class='ui-autocomplete-row'></li>" ) .data( "item.autocomplete", item ) .append( item.label ) .appendTo( ul ); }; }); </script>
HTML Code:
Define an HTML input element to attach the Autocomplete feature.
- If the user starts typing, the suggestions will be retrieved from the server-side source, and autocomplete drop-down will appear under the input field.
- Once you select an item from the auto-suggestion list, it will assign the respective ID to a hidden input field (userID) for the form submission process.
<!-- Autocomplete input field --> <input id="searchInput" placeholder="Enter member name..." autocomplete="off"> <!-- Hidden input for user ID --> <input type="hidden" id="userID" name="userID" value=""/>
SEE ALSO: Add WYSIWYG HTML Editor to Textarea with CKEditor
Database Configuration (dbConfig.php)
You can use the dbConfig.php file to connect and select the database. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your MySQL server credentials.
<?php // Database configuration $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = "root"; $dbName = "allsweb"; // Create database connection $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); // Check connection if ($db->connect_error) { die("Connection failed: " . $db->connect_error); }
Autocomplete Data with Images and Custom HTML (getUsers.php)
The getUsers.php is loaded by the autocomplete() method of jQuery UI Autocomplete plugin.
- The autocomplete() method creates a GET request to source URL (getUsers.php) and adds term parameter in the query string.
- Use PHP $_GET method to retrieve the value of the search term.
- Get the matched user’s data (filter by search term) from the database (users table) using PHP and MySQL.
- Attach user image, last name, and first name with HTML elements to the label.
- Create an array with the filtered data.
- Render filtered users data as JSON format.
<?php // Include database config file require_once 'dbConfig.php'; // Get search term $searchTerm = $_GET['term']; // Get matched data from the database $query = "SELECT id, first_name, last_name, image FROM users WHERE (first_name LIKE '%".$searchTerm."%' OR last_name LIKE '%".$searchTerm."%') AND status = '1' ORDER BY first_name ASC"; $result = $db->query($query); // Generate users data array $userData = array(); if($result->num_rows > 0){ while($row = $result->fetch_assoc()){ $name = $row['first_name'].' '.$row['last_name']; $data['id'] = $row['id']; $data['value'] = $name; $data['label'] = ' <a href="javascript:void(0);"> <img src="images/users/'.$row['image'].'" width="50" height="50"/> <span>'.$name.'</span> </a>'; array_push($userData, $data); } } // Return results as json encoded array echo json_encode($userData);
SEE ALSO: Auto Resize Textarea Height using jQuery
Conclusion
Firstly, if you want to integrate the member’s search feature, this jQuery Autocomplete textbox with images is beneficial to create the search input user-friendly. Secondly, the sample code explains you to add images, text, and custom HTML in the autocomplete widget. At last, you can increase this script to customize the autocomplete dropdown and render HTML elements.
Also, read our previous blog- Create Short URL using PHP URL Shortener