jQuery add/remove css class on selected radio

前端 未结 4 741
夕颜
夕颜 2021-01-05 15:33

I\'ve read a few solutions on here, but my problem differs enough where those will not work. Basically if the radio button is checked, add a css class to the parent div. If

4条回答
  •  心在旅途
    2021-01-05 16:02

    I had a similar issue but I needed to target the radio button's label instead of a parent div element. I also needed to make sure the other related label elements did not have the class.

    Here's what I came up with based on @user113716's answer:

    HTML

    MVC code removed so there is only HTML in this example

    jQuery

    $(':radio').click(function () {
        var _groupName = $(this).attr('name'),
            _radioId = $(this).attr('id'),
            _radioGroup = $(':radio[name="' + _groupName + '"]');
    
        //remove class from all labels for this group of radio buttons
        _radioGroup.each(function(){
            $('label[for*="' + $(this).attr('id') + '"]').removeClass('style1');
        });
    
        //add the class to the selected radio button
        $('label[for*="' + _radioId + '"]').addClass('style1');
    });
    

提交回复
热议问题