JavaScript/jQuery SelectBox - Customize Item Appearance

For a minor customization of SelectBox items, you can define specific fields in their 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() {
  • $("#selectBoxContainer").dxSelectBox({
  • valueExpr: 'text',
  • displayExpr: 'text',
  • dataSource: [
  • { text: "HD Video Player" },
  • { text: "SuperHD Video Player", disabled: true },
  • { text: "SuperPlasma 50", visible: false }
  • ],
  • placeholder: "Select a product..."
  • });
  • });

If you need a more flexible solution, specify itemTemplate.

JavaScript
  • const selectBoxData = [{
  • id: 1,
  • name: "HD Video Player",
  • imgSrc: "images/products/1-small.png"
  • }, {
  • id: 2,
  • name: "UltraHD Player",
  • imgSrc: "images/products/2-small.png"
  • },
  • // . . .
  • ];
  •  
  • $(function() {
  • $("#selectBoxContainer").dxSelectBox({
  • dataSource: selectBoxData,
  • valueExpr: 'id',
  • displayExpr: 'name',
  • itemTemplate: function (itemData, itemIndex, itemElement) {
  • return $("<div />").append(
  • $("<img />").attr("src", itemData.imgSrc),
  • $("<p />").text(itemData.name)
  • .css("display", "inline-block")
  • );
  • }
  • });
  • });

You can also customize individual SelectBox items. Declare them as scripts and reference them in the template property or assign a customization function straight to this property.

HTML
JavaScript
  • <div id="selectBoxContainer"></div>
  • <script id="individualTemplate" type="text/html">
  • <span>Comment</span>
  • </script>
  • $(function() {
  • $("#selectBoxContainer").dxSelectBox({
  • items: [{
  • template: function() {
  • return $("<span>").text("User");
  • }
  • }, {
  • template: $("#individualTemplate")
  • }]
  • });
  • });

Using similar techniques, you can customize the input field of the SelectBox. The template for it should be assigned to the fieldTemplate property. Note that the input field must contain the TextBox UI component.

JavaScript
  • $(function() {
  • $("#selectBoxContainer").dxSelectBox({
  • dataSource: selectBoxData,
  • valueExpr: 'id',
  • displayExpr: 'name',
  • value: 1,
  • fieldTemplate: function(selectedItem, fieldElement) {
  • return $("<div />").append(
  • $("<img />").attr("src", selectedItem.imgSrc),
  • $("<div />").dxTextBox({ value: selectedItem.name })
  • .css("display", "inline-block")
  • );
  • }
  • });
  • });
See Also