Henk Z Henk Z - 5 months ago 12
jQuery Question

jQuery add class to radio box not removed

I use jQuery to add a class to a radio box if it is selected.
That works fine, but it does not removed the class when selecting another radio box.

What am I missing?

jQuery(".checkbox-radio").change(function() {
if ($(this).is(':checked'))
$(this).closest(".radio-inline").addClass("selected");
else
$(this).closest(".radio-inline").removeClass("selected");
});


<label class="radio-inline conf-option-1">
<input type="radio" class="checkbox-radio" name="configoption[1]" value="1" checked="checked" onclick="prodconfrecalcsummary()">
<i class="icon-addon"></i>
<span class="addon-qty"></span>
<span class="addon-text">Text</span>
<span class="addon-price"> Text </span>
</label>

<label class="radio-inline conf-option-2">
<input type="radio" class="checkbox-radio" name="configoption[2]" value="2" checked="checked" onclick="prodconfrecalcsummary()">
<i class="icon-addon"></i>
<span class="addon-qty"></span>
<span class="addon-text">Text</span>
<span class="addon-price"> Text </span>
</label>

<label class="radio-inline conf-option-3">
<input type="radio" class="checkbox-radio" name="configoption[3]" value="3" checked="checked" onclick="prodconfrecalcsummary()">
<i class="icon-addon"></i>
<span class="addon-qty"></span>
<span class="addon-text">Text</span>
<span class="addon-price"> Text </span>
</label>

Answer

Remove selected class from all .radio-inline and then add/remove selected as per condition as shown below.

<script>
jQuery(".checkbox-radio").change(function() {
  $(".radio-inline").removeClass("selected"); //add this
  if ($(this).is(':checked')){
    $(this).closest(".radio-inline").addClass("selected");
  }
  else
    $(this).closest(".radio-inline").removeClass("selected");
});
</script>

DEMO

Comments