AKor AKor - 1 month ago 6
HTML Question

Applying styling to a checked radio button's parent

So I have a series of radio buttons inside

<li>
elements. I'm trying to create a border on said
<li>
only when its child radio button is checked.

I have a halfway solution here in jQuery:

$('input[type="radio"]').change(function() {
if($(this).is(':checked'))
{
$(this).parent().css('border', '1px solid black');
}
else
{
$(this).parent().css('border', 'none');
}
});


However, this only will add the style, but will not remove it when a different option in the radio buttons is selected. So, if you click all of the options, they all end up having the style applied.

What can I do here?

Answer

You'll have to remove the style on the other LI elements whenever a radio button is changed

var lis = $('input[type="radio"]').change(function() {
    lis.css('border', 'none');

    if ($(this).is(':checked') ) { 
        $(this).parent().css('border', '1px solid black');
    } 
}).parent(); // gets all the parents
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
    <li><input type="radio" name="group"></li>
    <li><input type="radio" name="group"></li>
    <li><input type="radio" name="group"></li>
</ul>