Matthew Cox
Matthew Cox

Reputation: 13672

Add class to selected option of a select element

To demonstrate that I could even use a Class attribute on an option elem I tried adding class attributes to options of a select elem in a static page and that works fine. I noticed that not many online resouces documented this so I figured I would explicitly set the record.

here is the jquery code attempting to add a class to the selected option

 ChangeDdlItemBG : function(obj, compLev)
{
    var ddl = $(obj);
    var index = ddl.attr('selectedIndex');
    switch(compLev)
    {
        case ComplianceLevel.Compliant : 
            $(ddl.attr('id') + ': selected').addClass('Compliant');
            break;
        case ComplianceLevel.OtherThanSerious : 
            $(ddl.attr('id') + ': selected').addClass('OtherThanSerious');
            break;
        case ComplianceLevel.Serious : 
            $(ddl.attr('id') + ': selected').addClass('Serious');
            break;
        case ComplianceLevel.Critical : 
            $(ddl.attr('id') + ': selected').addClass('Critical');
            break;
    }
}

var ComplianceLevel =
{
    Compliant : function() { return 0; },
    OtherThanSerious : function() { return 1; },
    Serious : function() { return 2; },
    Critical : function() { return 3; },
};

New information, I found the reason nothing occured was a simple mistake in the value being passed in for compLev. However, now it runs through the code for the correct case and does nothing to the color of the item.

Upvotes: 0

Views: 511

Answers (2)

Šime Vidas
Šime Vidas

Reputation: 185933

You can certainly reduce the redundancy.

Also, you have to run the functions, in order to compare their return value with compLev:

function(obj, compLev) {

    var optClass = "";

    switch (compLev) {
    case ComplianceLevel.Compliant() : 
        optClass = 'Compliant';
        break;
    case ComplianceLevel.OtherThanSerious() : 
        optClass = 'OtherThanSerious';
        break;
    case ComplianceLevel.Serious() : 
        optClass = 'Serious';
        break;
    case ComplianceLevel.Critical() : 
        optClass = 'Critical';
        break;
    }

    $(obj).find("option:selected").addClass(optClass).siblings().removeClass();

}

Upvotes: 1

shoebox639
shoebox639

Reputation: 2312

It looks like your selectors have a typo. Unless ddl.attr('id') is a type of element, your code doesn't add classes to anything. I think you want $('#' + ddl.attr('id') + ':selected')

Upvotes: 0

Related Questions