Applying Style to a Tested Switch

So, I have a series of radio buttons inside the elements <li>. I try to create a border on the specified <li>only when its child switch is checked.

I have a solution half 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 will only add a style but will not delete it if another option is selected in the radio buttons. So, if you click on all options, they will all have a style.

What can i do here?

+4
source share
1 answer

Each time you change the switch, you will have to remove the style on the other LI elements

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>
Run codeHide result
+5
source

Source: https://habr.com/ru/post/1658843/


All Articles