Search code examples
asp.net-mvc-4colorshtml.dropdownlistfor

@Html.DropDownListFor - How to set different color for a single item in list?


I wish to have one item in my DDL to be a different color (red). However the list comes from a table and is not hard coded in the page like

<option value="Option 1">Option 1</option>

but rather as

@Html.DropDownListFor(r => r.Journal.Frequency, Model.JournalFrequencyList, "Select a Frequency", new { @class = "form-control" })

Is there a way to make just one item a different color?


Solution

  • You can update your styles/css to make one item red color. Now you did not specify which specific item you want. With jQuery, you can select a specific option and set the color of that to red.

    Assume your razor view renders a SELECT element like this

    <SELECT id="fancySelect">
        <option value="1">One</option>
        <option value="2">Two</option>
       <option value="3">Three</option>
    </SELECT>
    

    And if you want to set the color of the option which has value attribute set to "2", you can use the below code

    $(function(){
    
        $("#fancySelect option[value='2']").css('color','red');
        //you can also apply a css class if needed
    
    });
    

    If you want to update a different option, update your jQuery selector to get that.

    EDIT : As per the comment

    is there any way to use the text as opposed to the value? Example change if text is "Deleted"

    You can update your jQuery selector to get the option with a specific text.

    $("#fancySelect").find("option:contains('Deleted')").css('color','red');
    

    I suggest you rely on option value than the text, you can set the value as a code which you can program against.