jQuery UI - changing button colours

Nick picture Nick · May 10, 2012 · Viewed 21.7k times · Source

Using jQuery UI I have two radio buttons, Approve/Reject, which I would like to style independantly, so when 'Approve' is selected, it will be blue, and when 'Reject' is selected, it will be red:

Nothing selected

Approve selected

Reject selected

Apologies for my terrible red button mockup :-) Hopefully this will give you an idea of what I'm after. I've tried changing the class of both buttons/labels, but this isn't then reflected onto the jQuery-UI overlay.

Here's my current code that is generating the buttons, and also displaying a tick or a cross depending on the selection:

$('.approvedToggle').buttonset();

$('input:radio').click(function() {
    if($(this).val() === 'approve') {
        $(this).parent('div').children(".tick").show();
        $(this).parent('div').children(".cross").hide();
    } else {
        $(this).parent('div').children(".tick").hide();
        $(this).parent('div').children(".cross").show();
    }
});

Any help would be much appreciated - thanks!

Answer

Code Maverick picture Code Maverick · May 10, 2012

What you need to do is override the jQuery UI default styling.

Here's what the documentation states:

If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.button.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<button class="ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all"> <span class="ui-button-text">Button Label</span> </button>

So basically, what you can do, is something like this:

HTML:

<div id="approvedToggle">
    <input type="radio" id="ApproveButton" name="radio" />
    <label id="ApproveButtonLabel" for="ApproveButton">Approve</label>

    <input type="radio" id="RejectButton" name="radio" />
    <label id="RejectButtonLabel" for="RejectButton">Reject</label>
</div>​


CSS (Important! This styling MUST be declared AFTER the jQuery UI CSS file):

#ApproveButtonLabel.ui-state-active { background: blue; }
#ApproveButtonLabel.ui-state-active span.ui-button-text { color: red; }

#RejectButtonLabel.ui-state-active { background: red; }
#RejectButtonLabel.ui-state-active span.ui-button-text { color: blue; }


jQuery:

$('#approvedToggle').buttonset();​


Output:

enter image description here


See the working jsFiddle demo