lizw
lizw

Reputation:

radio button change style on checked

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!

Upvotes: 3

Views: 2333

Answers (2)

Josh Stodola
Josh Stodola

Reputation: 82483

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");
});

Upvotes: 0

mck89
mck89

Reputation: 19231

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.

Upvotes: 4

Related Questions