views:

165

answers:

2

i have a set of radio buttons.

<ul class="ProductOptionList">
<li>
<label>
<input class="RadioButton" type="radio" value="157" name="variation[1]"/>
Lemon (200 ml)
</label>
</li>
<li>
<label>
<input class="RadioButton chosen" type="radio" value="160" name="variation[1]"/>
Lemon and Herbs (200 ml)
</label>
</li>
</ul>

i want to highlight the one that is selected.

i used this code:

$('input.RadioButton').click(function() {
    var chkbox = $(this);
      chkbox.is(':checked') ?
        chkbox.addClass('chosen') : $chkbox.removeClass('chosen');

but if a person clicks one variation it works and applies the class, then if they click a second it applies the class to the second but doesnt remove the class from the first. how do i remove the class? thanks!

+4  A: 

Because you activate the function only on the clicked radio. Try this:

$("input.RadioButton").click(function(){
   $("input.RadioButton").removeClass('chosen');
   $(this).addClass('chosen');
})

In this way you remove the "chosen" class from all radios and then you assign the class only on the clicked one.

mck89
thanks! i knew that was the problem, i just couldnt figure out how to fix it.
A: 

First of all, you do not need to have "RadioButton" as a class because you can select them via attribute like this...

$("input[type=radio]")

Secondly, you should remove the chosen class before applying it to this...

$("input[type=radio]").click(function() {
  // Remove the class from all inputs that have it
  $("input[type=radio].chosen").removeClass("chosen");

  // Add it to current
  $(this).addClass("chosen");
});
Josh Stodola