jQuery radio onchange toggle class of parent element?

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

    Here is the solution which worked great for me:

    var $boxes=$('input:radio');
    var $parents = $boxes.parent();
    $boxes.click(function(){
        $parents.filter('.selected').removeClass('selected');
        $(this).parent().addClass('selected');
    });
    $boxes.filter(':checked').parent().addClass('selected');
    

    Features:

    • Faster. Only selects list of checkboxes once.
    • Does not rely on :checked. I'm not sure if there is a certain order in which "clicked" and "changed" will be executed across browsers.
    • uses :radio instead of [type="radio"] which is jQuery recommended
    • sets class on the parent for the default value of radio button.

    Hope this helps!

提交回复
热议问题