JavaScript/jQuery Autocomplete - Customize Item Appearance

For a minor customization of Autocomplete items, you can define specific fields in item data objects. For example, the following code generates three items: the first is not customized, the second is disabled and the third is hidden.

JavaScript
  • $(function() {
  • $("#autocompleteContainer").dxAutocomplete({
  • valueExpr: "text",
  • dataSource: [
  • { text: "James" },
  • { text: "John", disabled: true },
  • { text: "Joseph", visible: false }
  • ],
  • placeholder: "Type first name..."
  • });
  • });

If you need a more flexible solution, define an itemTemplate.

JavaScript
  • const autocompleteData = [
  • { country: "Afghanistan", capital: "Kabul" },
  • { country: "Albania", capital: "Tirana" },
  • // ...
  • ];
  •  
  • $(function() {
  • $("#autocompleteContainer").dxAutocomplete({
  • dataSource: autocompleteData,
  • valueExpr: 'country',
  • placeholder: 'Type country name...',
  • itemTemplate: function (itemData, itemIndex, itemElement) {
  • itemElement.append("<p>Country: <b>" + itemData.country + "</b></p>");
  • itemElement.append("<p style='color:grey;'>Capital: <b>" + itemData.capital + "</b></p>");
  • }
  • });
  • });

You can also customize an individual Autocomplete item. For this purpose, declare a template for this item as a script and pass its id to the template field.

HTML
JavaScript
  • <script id="individualTemplate" type="text/html">
  • <!-- ... -->
  • </script>
  • const autocompleteData = [
  • { text: "James"},
  • { text: "Joseph", template: $("#individualTemplate") },
  • // ...
  • ];
See Also