0

Hie, I want to add a CSS class to a particular SelectListIem in DropDowList in MVC Razor syntax.

I actually want to implement a CSS for:

new SelectListItem{ Text="Out Of 5", Value = "Out Of 5"},

instead of implementing for the entire control.

Below is the code snippet:

@Html.DropDownList("Options", new List<SelectListItem>
{
   new SelectListItem{ Text="Select Options", Value = "1" },
   new SelectListItem{ Text="CheckBox", Value = "1" },
   new SelectListItem{ Text="Radio", Value = "2" },
   new SelectListItem{ Text="Rating", Value = "3"},
   new SelectListItem{ Text="Out Of 5", Value = "Out Of 5"},
   new SelectListItem{ Text="Out Of 10", Value = "Out Of 10"},
   new SelectListItem{ Text="Text", Value = "4"},
}, new { @class = "form-control input-group, dropdown-submenu" })







                            
    
                           

1 Answer 1

1

Here are two solutions:

First one(foreach options of dropdown,and if text="Out Of 5",add class to it):

@Html.DropDownList("Options", new List<SelectListItem>
{
   new SelectListItem{ Text="Select Options", Value = "1" },
   new SelectListItem{ Text="CheckBox", Value = "1" },
   new SelectListItem{ Text="Radio", Value = "2" },
   new SelectListItem{ Text="Rating", Value = "3"},
   new SelectListItem{ Text="Out Of 5", Value = "Out Of 5"},
   new SelectListItem{ Text="Out Of 10", Value = "Out Of 10"},
   new SelectListItem{ Text="Text", Value = "4"},
}, new { @class = "form-control input-group, dropdown-submenu",@id="select" })
<script>
    $(function () {
        $("#select > option").each(function () {
            if (this.text == "Out Of 5") {
                $(this).addClass("special");
            }
        });
    })
</script>
<style>
    .special {
        color:red;
    }
</style>

2.Second one(change selectlistItem to ,and add class to <option value="Out Of 5" class="special">Out Of 5</option>):

<select class="form-control input-group, dropdown-submenu">
    <option value="1">Select Options</option>
    <option value="1">CheckBox</option>
    <option value="2">Radio</option>
    <option value="3">Rating</option>
    <option value="Out Of 5" class="special">Out Of 5</option>
    <option value="Out Of 10">Out Of 10</option>
    <option value="4">Text</option>
<style>
    .special {
        color:red;
    }
</style>

result: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.