Search code examples
jqueryradio-buttonshow-hideselected

Looping through radio buttons, hiding unslected ones


I have groups of radio buttons, what I am trying to do is to loop through and hide the radio and label of any unselected ones (addClass .hiddenRadio). The other side of this is I need to enable them again on another event click

<input class="radio" type="radio" name="sex_1" value="male" /><label>Male</label>
<input class="radio" type="radio" name="sex_1" value="female" /><label>Female</label>

<input class="radio" type="radio" name="sex_2" value="male" /><label>Male</label>
<input class="radio" type="radio" name="sex_2" value="female" /><label>Female</label>

Male Female


Solution

  • See the following which selects all unchecked inputs with the radio class and hides the corresponding label:

    $(".radio:not(:checked)").each(function() {
        // If you the hiddenRadio class added to both
        $(this).addClass("hiddenRadio").next().addClass("hiddenRadio");
    
        // Otherwise if you just want to hide the label
        $(this).addClass("hiddenRadio").next().hide();
    });