In jQuery UI Autocomplete, you can customize the display of the autocomplete results to show more than one value per item. By default, jQuery UI Autocomplete only displays one value (label) in the dropdown list, but you can modify this behavior using the renderItem
option.
Here's how you can achieve this:
- HTML: Create an input field where you want to apply the autocomplete feature.
html<input type="text" id="autocompleteInput">
- JavaScript:
Initialize the jQuery UI Autocomplete and use the
renderItem
option to customize the display of each item in the dropdown list.
html<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function() {
// Sample data with multiple values for each item
const data = [
{ value: 1, label: "Item 1", description: "Description 1", price: "$10.00" },
{ value: 2, label: "Item 2", description: "Description 2", price: "$20.00" },
{ value: 3, label: "Item 3", description: "Description 3", price: "$15.00" },
// Add more items here
];
// Initialize the autocomplete
$("#autocompleteInput").autocomplete({
source: data,
minLength: 0,
focus: function(event, ui) {
// Prevent the input from being updated with the focused item's value
event.preventDefault();
},
select: function(event, ui) {
// Set the input value when an item is selected
$("#autocompleteInput").val(ui.item.label);
return false;
},
// Customize the display of each item in the dropdown list
// Here, we are showing the label, description, and price
// in a custom format for each item
renderItem: function(ul, item) {
return $("<li>")
.append("<div>" + item.label + "</div>")
.append("<div>" + item.description + "</div>")
.append("<div>" + item.price + "</div>")
.appendTo(ul);
},
});
// Show autocomplete dropdown when the input is focused
$("#autocompleteInput").on("focus", function() {
$(this).autocomplete("search", "");
});
});
</script>
In this example, we initialize the autocomplete on the #autocompleteInput
element with a sample dataset containing multiple values (label, description, and price) for each item. The renderItem
option is used to customize the display of each item in the dropdown list. The focus
event handler prevents the input from being updated with the focused item's value when the user navigates through the dropdown list.
You can modify the data
array with your actual dataset, and customize the renderItem
function to display any desired values or formatting for each item in the dropdown list.