JavaScript/jQuery Autocomplete - Add Tooltips to Items

The useItemTextAsTitle property adds a title attribute to each item element with the item's display text. The browser displays this text as a native tooltip when a user hovers over the item.

JavaScript
  • $(function() {
  • $("#autocompleteContainer").dxAutocomplete({
  • useItemTextAsTitle: true,
  • items: [
  • { id: 1, name: "Item 1" },
  • { id: 2, name: "Item 2" }
  • ],
  • displayExpr: "name",
  • valueExpr: "id"
  • });
  • });

If you use a custom itemTemplate, add a title attribute to the root element of the template to display the item text as a native browser tooltip:

JavaScript
  • $(function() {
  • $("#autocompleteContainer").dxAutocomplete({
  • items: [
  • { id: 1, name: "John Doe", email: "john@example.com" },
  • { id: 2, name: "Jane Smith", email: "jane@example.com" }
  • ],
  • displayExpr: "name",
  • valueExpr: "id",
  • itemTemplate: function(itemData) {
  • return $("<div>")
  • .attr("title", itemData.name)
  • .append($("<b>").text(itemData.name))
  • .append($("<br>"))
  • .append($("<small>").text(itemData.email));
  • }
  • });
  • });

To display a styled Tooltip with custom content, initialize the Tooltip component inside itemTemplate:

JavaScript
  • $(function() {
  • $("#autocompleteContainer").dxAutocomplete({
  • items: [
  • { id: 1, name: "Item 1", description: "Detailed description 1" },
  • { id: 2, name: "Item 2", description: "Detailed description 2" }
  • ],
  • displayExpr: "name",
  • valueExpr: "id",
  • itemTemplate: function(itemData, index, element) {
  • const itemEl = $("<span>")
  • .text(itemData.name)
  • .appendTo(element);
  •  
  • $("<div>").dxTooltip({
  • target: itemEl,
  • showEvent: "mouseenter",
  • hideEvent: "mouseleave",
  • contentTemplate: function() {
  • return itemData.description;
  • }
  • }).appendTo(element);
  • }
  • });
  • });

You can replace "mouseenter" and "mouseleave" with other events such as "click", "dblclick", "focus", or "blur" to control when the Tooltip is displayed.

To display a tooltip only for truncated items, compare element.scrollWidth with element.clientWidth and set the title attribute or display the Tooltip conditionally.

To display HTML content in the tooltip, return an HTML string from contentTemplate in the Tooltip component or from itemTemplate.