This is a migrated thread and some comments may be shown as answers.

Can I set the background color of each individual item in the dropdown?

2 Answers 1578 Views
DropDownList
This is a migrated thread and some comments may be shown as answers.
Randy
Top achievements
Rank 1
Randy asked on 18 Nov 2019, 03:14 PM

I have a Kendo MVC dropdown list that looks like what you see below. I would like to set the background color of each item in the list based on information contained in the Employee entity being returned from the read operation. Note, I won't be able to use any sort of class to do this because I won't know ahead of time what the color should be. The color will be contained in each Employee entity returned. Can this be done?

                @(Html.Kendo().DropDownListFor(m => m)

                    .Name("EmployeeDropDown")
                    .DataTextField("DropDownText")
                    .DataValueField("RowId")
                    .OptionLabel("Select Employee...")
                    .AutoBind(false)
                    .Filter("contains")
                    .HtmlAttributes(new { style = "width: 525px" })
                    .DataSource(source =>
                    {
                        source.Read(read =>
                        {
                            read.Action("GetEmployeesForDropDown", "Employee");
                        })
                        .ServerFiltering(true);                                     // Let's do server side filtering
                    })
                    .Events(e => {
                        e.Select("onSelect");
                    })

2 Answers, 1 is accepted

Sort by
0
Martin
Telerik team
answered on 20 Nov 2019, 11:55 AM

Hello Randy,

Thank you for the provided code. You can do that by binding to the dataBound event. By using the items method of the DropDownlist, you can get all the items as DOM elements. After iterating them, you can use the dataItem method for each element, which will give you access to the "Color" property in the Model. You can then set the background-color for the current DOM element:

function onDataBound(e) {
    var ddl = e.sender;
    var items = ddl.items(); 
    for (let item of items) {
        var dataItem = ddl.dataItem($(item));
        $(item).css("background-color", dataItem.Color);
    }
}

Attached you will find a project demonstrating the approach.

Feel free to contact us if you have questions regarding the approach.

Regards,
Martin
Progress Telerik

Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
0
Randy
Top achievements
Rank 1
answered on 20 Nov 2019, 01:53 PM
This worked perfectly. Thank you.
Tags
DropDownList
Asked by
Randy
Top achievements
Rank 1
Answers by
Martin
Telerik team
Randy
Top achievements
Rank 1
Share this question
or