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.
- $(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. In Angular and Vue, you can declare it in the markup. In React, you can use a render function or component as shown in the following example:
If you use jQuery, use DOM manipulation methods to create HTML markup for items. To apply this markup, use the itemTemplate callback function as shown in the following code:
- 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 an individual SelectBox item. In Angular, Vue, and React, declare them using the dxItem component. In jQuery, you can declare the items as scripts and reference them in the template property or assign a customization function straight to this property:
- <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.
- $(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")
- );
- }
- });
- });
In addition, you can use a 3rd-party template engine to perform the needed customizations. For more information, see the 3rd-Party Template Engines article.
See Also
If you have technical questions, please create a support ticket in the DevExpress Support Center.