LeBlaireau
LeBlaireau

Reputation: 17467

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

Upvotes: 0

Views: 1982

Answers (3)

Anders Marzi Tornblad
Anders Marzi Tornblad

Reputation: 19305

Two lines of code is really enough:

$("input[type=radio]:not(:checked)").addClass("hiddenRadio");
$("input[type=radio]:not(:checked) + label").addClass("hiddenLabel");

No need for loops using each() or manually finding labels using next() - just let the selectors do their job!

Here is a jsfiddle to demonstrate (not hiding, but changing color):

http://jsfiddle.net/bZcHq/

Also, there is no need for adding class='radio' to every radio button. The attribute selector [type=radio] will suffice, as long as you don't plan on supporting IE6.

Upvotes: 3

Dutchie432
Dutchie432

Reputation: 29160

How about something like this: http://jsfiddle.net/GTzL4/4/

HTML

<input class="radio" type="radio" name="sex_1" value="male" checked /><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" checked /><label>Female</label>

<button onclick="hideUnSelected()">Hide</button>
<button onclick="showAll()">Show</button>

CSS

.hidden{display:none;}

JS

function hideUnSelected(){
    $('.radio:not(:checked)').each(function(){
        $(this).addClass('hidden').next('label').addClass('hidden');
    });
}
function showAll(){
    $('.radio').each(function(){
        $(this).removeClass('hidden').next('label').removeClass('hidden');
    });
}

Upvotes: 0

Phil Klein
Phil Klein

Reputation: 7514

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();
});

Upvotes: -1

Related Questions