jQuery radio onchange toggle class of parent element?

前端 未结 7 965
无人及你
无人及你 2021-01-11 19:28

Please have a look on the following:

$(\'#myRadio\').change(function() {           

    if($(this).is(\':checked\'))  {
        $(this).parent().addClass(\'         


        
7条回答
  •  执念已碎
    2021-01-11 19:50

    I just wrote a solution that does not care how deeply nested the radio buttons are, it just uses the name attribute of the radio buttons. This means this code would work without modification anywhere, I think - I had to write it since I have a strange situation where one radio button is nested differently than its cohorts with the same name.

    $('input[type="radio"]').change( function() {
        // grab all the radio buttons with the same name as the one just changed
        var this_radio_set = $('input[name="'+$(this).attr("name")+'"]');
    
        // iterate through each  
        // if checked, set its parent label's class to "selected"
        // if not checked, remove the "selected" class from the parent label
        // my HTML markup for each button is  
        // so that this works anywhere even without a unique ID applied to the button and label
        for (var i=0; i < this_radio_set.length;i++) {
            if ( $(this_radio_set[i]).is(':checked') ) $(this_radio_set[i]).parents('label').addClass('selected');
            else $(this_radio_set[i]).parents('label').removeClass('selected');
        }
    });
    

提交回复
热议问题