<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?
$('.radio-btn').click(function() { if ($(this).is(':checked')) { $('.row').addClass("hvr"); } }); Code (markup):
Thank you. That worked but there's still a problem. 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.
Change the class of the div you want to change or if it is just one div you can add an id. <div class="row" id="radioBtn"></div> $('.radio-btn').click(function() { if ($(this).is(':checked')) { $('#radioBtn').addClass("hvr"); } }); Code (markup):
This works but there's still a problem: $('.radio-btn').click(function() { if( $(this).is(':checked')) { $(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.
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.
This works now. Problems solved! <script> $('.radio-btn').click(function() { $('.row').removeClass("hvr"); $(this).filter(':checked').closest('.row').addClass("hvr"); }); </script>