jQuery radio onchange toggle class of parent element?

前端 未结 7 967
无人及你
无人及你 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

    You shouldn't use the change() event on radio buttons and checkboxes. It behaves a little dodgy and inconsistent across browsers (it causes problems in all versions of IE)

    Use the click() event instead (don't worry about accessibility, because the click event will also be fired if you activate/select a radio button with the keyboard)

    And as the others here pointed out, resetting the green is easy as well:

    So simply change your code to

    $('#myRadio').click(function() {           
        $(this).parents("tr").find(".green").removeClass("green");
    
        if($(this).is(':checked'))  {
            $(this).parent().addClass('green');
        }
    });
    

    EDIT: as requested in comment, also change the previous td:

    $('#myRadio').click(function() {           
        $(this).parents("tr").find(".green").removeClass("green");
    
        if($(this).is(':checked'))  {
            $(this).parent().prev().andSelf().addClass('green');
        }
    });
    

    or even better, turning all td elements of the parent row green:

    $('#myRadio').click(function() {           
        $(this).parents("tr").find(".green").removeClass("green");
    
        if($(this).is(':checked'))  {
            $(this).parents("tr").find("td").addClass('green');
        }
    });
    

提交回复
热议问题