Bevels Bevels - 1 month ago 8
CSS Question

Targeting a div associated with a checked radio button using jQuery

HTML

<div class="container">
<div class="target"></div>
<input type="radio">
</div>

<div class="container">
<div class="target"></div>
<input type="radio">
</div>

<div class="container">
<div class="target"></div>
<input type="radio">
</div>


CSS

.target {
background-color: red;
}

.active {
background-color: blue;
}


jQuery

$(document).ready(function(){
$('.target').each(function(){
if ($('.container:has(input:radio:checked)')) {
$(this).addClass('active');
}
});
});


The above adds the class 'active' to all .target div's. What I need it to do is add an 'active' class to the .target div associated with the currently checked radio only.

I tried using
$(this).parent('div').addClass('active');
and various other things but I'm not winning :-S

Not sure if I should be using .each either?

Help is much appreciated!

Answer

Try modifying your jQuery like this:

$(document).ready(function(){
   $("input[type='radio']:checked").each(function(){
      $(this).parent().find(".target").addClass("active");
   }
   });
});
Comments