When button checked change background color of containing div

<script>
$('.radio-btn').click(function() {
    if( $(this).is(':checked')) {
      $document.getElementsByClassName("row").addClass("hvr");
    }
}); 
</script>

.hvr {
	background-color: #f2f2f2;
}

<div class="row"><input type="radio" class="radio-btn" name="payment-options"  /></div>

When I click on the radio button I want the background color of the containing div to change. What I have here isn’t working. Can anybody help?

The javascript didn’t show up. Here it is:

  <script>
     $('.radio-btn').click(function() {
        if( $(this).is(':checked')) {
          $document.getElementsByClassName("row").addClass("hvr");
        }
   }); 
   </script>

you have to tell disqus that it is supposed to be in a code section, see the </> button.

the solution is given in the other forum you posted in.

This works but there’s still a problem:

    <script>
      $('.radio-btn').click(function() {
          if( $(this).is(':checked')) {
     $('.row').addClass("hvr");
    }
}); 
</script>

I have several divs with the class of row and I only want the one containing the checked radio button to have a different background color.

the solution is given in the other forum you posted in.

1 Like

This works but there’s still a problem:

$('.radio-btn').click(function() {
     $(this).filter(':checked').closest('.row').addClass("hvr");
});

If the user changes his mind and clicks on a different radio button then it has to be highlighted as well. The way it works now it leaves the previously checked button’s div highlighted and then highlights the next one as well.

the solution is given in the other forum you posted in.

1 Like

This is the right code:

$('.radio-btn').click(function() {
		$(this).filter(':checked').closest('.row').addClass("hvr");

}); 

But there’s still the problem that the previously highlighted div remains highlighted when the next radio button is clicked.

that code is no different from the previous version.

Remove all .hvr classes and then just add the single one to the current element.

e.g.

$('.radio-btn').click(function() {
$('.row').removeClass("hvr");
$(this).filter(':checked').closest('.row').addClass("hvr");

});

Assuming you will only ever have one class of .hvr active.

Thank you! That worked.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.