Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Radio Buttons

Hi Folks,

Does anyone know how to change a background of label when a radio buttons is clicked? I have been messing about with javascript but haven't gotten anywhere.

Pretty much when the user clicks on the radio buttons I want the background to change to white with a left border of 1px solid #000.

http://www.testmethanks.com/test/index.html

I would appreciate any help on this, I have been going around in circles.

Thanks,

Mary

2 Answers

Given the following markup:

<label>
    <input type="radio" name="toppings" value="green peppers"/>
    Green Peppers
</label>

<label>
    <input type="radio" name="toppings" value="onions"/>
    Onions
</label>

<label>
    <input type="radio" name="toppings" value="pepperoni"/>
    Pepperoni
</label>

You could handle it with the following javascript:

    $('input[type=radio]').change(function(){
        $('label').removeClass('selected');
        $(this).parents('label').addClass('selected');
    });

Then just set your styles in label.selected.

Obviously this is the most basic of examples to achieve what you're looking for, but hopefully it'll be a good jumping off point for you to get started.

EDIT: Here's the above example in JSFiddle: http://jsfiddle.net/7vypL1q6/

That's a great help, Thank You. I haven't delved enough into javascript yet to get anything going smoothly.

Thanks again.