未加星标

jQuery UI Autocomplete with Images and Custom HTML in PHP

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

The jQuery UI Autocomplete plugin provides an instant way to add autocomplete suggestions feature to the textbox. It allows the user to quickly search and select a value from a pre-populated list. When the user starts typing in the input field, the Autocomplete plugin fetch the matched values and listed them under the textbox. You can easily integrate the autocomplete textbox functionality using jQuery UI,php, and mysql .

Generally, the Autocomplete widget fetch the values from the database and display the suggestions as text format under the input field. But, you can customize the autocomplete dropdown and suggestions list with custom HTML code. The custom autocomplete dropdown list is very useful when you want to maintain the design with webpage layout. In this tutorial, we will show you how to add custom HTML and show images and text in autocomplete using jQuery UI, PHP, and MySQL.

In the example 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, the matched members data will be fetched from the database. The member’s data with name and image will be listed in the auto suggestions dropdown. Create Database Table

To store the autosuggestions data a table needs to be created in the database. The following SQL creates a users table with some basic 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:

Include 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 initialize 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 an item is selected from the suggestions dropdown. On selecting an item, the value will be set to the autocomplete input field and 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 in the suggestion list of the widget. <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.

When the user starts typing, the suggestions are retrieved from the server-side source and autocomplete drop-down will appear under the input field. Once the user selects an item from the auto-suggestion list, the respective ID is assigned 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=""/> Database Configuration (dbConfig.php)

The dbConfig.php file is used 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 = "codexworld"; // 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 makes 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. Fetch the matched user’s data (filter by search term) from the database (users table) using PHP and MySQL. Add user image, first name, and last name with HTML elements to the label. Generate 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); Conclusion

If you want to integrate members search functionality, this jQuery Autocomplete textbox with images is very useful to make the search input user-friendly. The example code shows you to add images, text, and custom HTML in the autocomplete widget. You can easily extend this script to customize the autocomplete dropdown and render HTML elements. For the example of various configuration options of jQuery UI Autocomplete plugin, see this tutorial Autocomplete Textbox using jQuery, PHP and MySQL

Are you want to get implementation help, or modify or extend the functionality of this script?Submit paid service request

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

代码区博客精选文章
分页:12
转载请注明
本文标题:jQuery UI Autocomplete with Images and Custom HTML in PHP
本站链接:https://www.codesec.net/view/621234.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(22)