I have the following code in my template where radio button is selected when its wrapping/parent div is clicked.
Additionally I'm trying to change the background color to red and text color to white of the selected radio option.
If the radio option is unchecked reset its background color to default white and text color to black.
But with my code background and text of all select option is set to background color to white and text color to black.
How can I set option's background color to default white and text color to black if other option is selected.
Both Jquery and javascript approach is appreciated. Thanks.
$('.selectRadio').click(function(event) {
/* console.log($('.selectRadio').length) */
;
let element = $('.selectRadio');
let radButton = $(this).find('input[type=radio]');
for (let i = 0; i <= element.length; i++) {
/* $('selector').index(this) */
if (element.index(this) - 1 == i) {
console.log(element.index(this) - 1);
console.log(i);
radButton.prop("checked", true);
radButton.parent().css("background-color", "red");
radButton.parent().css("color", "white");
} else {
radButton.parent().css("background-color", "unset");
radButton.parent().css("color", "unset");
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="container">
<div class="row">
<div class="col-4 selectRadio">
<div class="radio">
<label><input type="radio" name="optradio" >Option 1</label>
</div>
</div>
<div class="col-4 selectRadio">
<div class="radio">
<label><input type="radio" name="optradio">Option 2</label>
</div>
</div>
<div class="col-4 selectRadio">
<div class="radio">
<label><input type="radio" name="optradio">Option 3</label>
</div>
</div>
</div>
</div>