dinotom
dinotom

Reputation: 5162

change selected radio button textcolor in jquery

I am trying to change the text color on the selected radio button's text when it is checked ( a group of three). It doesn't work. I've tried multiple variations but this should be working

$(document).ready(function() {
    if (
    $('.radioPanel [input:radio]').is(":checked")) {
        $(this).css('color', '#008000');
    }
});

Here is the aspx code; is the outer code affecting the jquery changes?

<fieldset class="registerradio">
                    <legend>Select a Category</legend>
                  <asp:Panel ID="radiobtnPanel" runat="server" CssClass="radioPanel">
                    <asp:RadioButton ID="radioUserEmployee" runat="server" GroupName="radioCreateUsers" Text="Employee" TextAlign="Left"  />
                    <asp:RadioButton ID="radioUserDistributor" runat="server" GroupName="radioCreateUsers" Text="Distributor" TextAlign="Left"/>
                    <asp:RadioButton ID="radioUserCustomer" runat="server" GroupName="radioCreateUsers" Text="Existing Customer" TextAlign="Left"/>
                    <%--<asp:RadioButton ID="radioUserOther" runat="server" GroupName="radioCreateUsers" Text="Other" TextAlign="Left"/>--%>
                  </asp:Panel>
 </fieldset>

Here is the fiddle; http://jsfiddle.net/6yVL3/

Upvotes: 1

Views: 7008

Answers (3)

Chao Zhang
Chao Zhang

Reputation: 1534

Try this:

$('.radioPanel input[type="radio"]').change(function() {
    if ($(this).is(':checked')) 
        $(this).prev('label').css('color', '#008000');
});​

By the way, you should remove the color of the label previously checked. Like this:

$('.radioPanel input[type="radio"]').change(function() {
    $('.radioPanel label').css('color', 'black');
    //This in result removes the color of the label checked previously, in fact it just resets all the color of labels to black
    if ($(this).is(':checked'))
       $(this).prev('label').css('color', 'green');
});

DEMO.

Upvotes: 3

muthu
muthu

Reputation: 5461

You may try like this

$(document).ready(function() {

 $(".radioPanel :input:checked").prev('label').css('color', '#008000');

});​

Upvotes: 1

Calvein
Calvein

Reputation: 2121

There were some errors in your JavaScript :

  • You set mootools instead of jQuery in jsFiddle
  • Your selector was wrong, it's [attr=value], check the list here
  • Your JavaScript was static, it means that you check just once if the radio was checked, if there was changes, nothing happen
  • You set the color to the radio and not the label

Here is the code :

$(function() {
    // When the value of the radio change
    $('.radioPanel [type="radio"]').on('change', function() {
        $(this)
        .prev().css('color', 'red')
        .siblings().css('color', 'black');
    });
});​

And here is the live example.

Upvotes: 6

Related Questions