Changing the colour of a specific item in the Select2 DropDown


#1

Hello guys, so, I am working with asp.net Webforms and Select2 and I have this:

     $(document).ready(function () {            

      $("#<%=ddl_modelo_equipamento.ClientID%>").select2({

          placeholder: "Selecione um Modelo"

      });

  });

And in my code behind I had a code to change the colour of specific items when a string in the item contained “stocks”, I wanted to change the colour to red, but it doesn’t change.
How can I change the colour of a specific item in the Select DropDown based on that??

By the way, the Dropdown is being loaded with information from the DataBase.

P.S:
I don’t know if you guys want the code behind or if it is relavant, but I’ll leave it here the function that should change the colour and it isn’t:

private void changeColor(DropDownList ddl_modelo_equipamento)
{
foreach (ListItem item in ddl_modelo_equipamento.Items)
{
string descricao = item.Text;

            if (descricao.Contains("; Stock: 0 unid."))
            {
            
                item.Attributes.Add("style", "color:red");
                continue;
            }
        }
    }

#2

You will probably need to use a custom templateResult function to output items that contain the word “stocks” in a span element with a class that can be styled via CSS to display in red. (You could also inline the style attribute’s value in the span tag, but using a CSS class is the better approach.) Note that you must output your spanelement as a jQuery object, otherwise Select2 will escape the HTML instead of rendering it. See the link above for details.