JGeer
JGeer

Reputation: 1852

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>

Upvotes: 3

Views: 103

Answers (4)

Mani
Mani

Reputation: 2655

Use like this

$(".radio-inline").click(function() {

    $(".radio-inline").find("input").removeClass("selected");

    if ($(this).find("input").is(':checked')){      
        $(this).find("input").addClass("selected");
    }

});

Upvotes: 0

D V Yogesh
D V Yogesh

Reputation: 3700

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

Upvotes: 0

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

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

Upvotes: 1

AlexBerd
AlexBerd

Reputation: 1504

The name attribute should  be the same for all your check-boxes
See here:

JSFIDDLE

Upvotes: 1

Related Questions