Question

I'm kind of stuck on something...

my else statement doesn't seem to be working right.

<div class="main-options">
    <label class="main-label" for="main-options">Main Options:</label>
    <input class="option-a" type="radio" name="main-options">
    <label for="main-options">Option A</label>
    <input class="option-b" type="radio" name="main-options">
    <label for="main-options">Option B</label>
</div>

<div class="sub-options">
    <label class="sub-options-label" for="sub-options">Sub Options:</label>
    <input class="option-c" type="radio" name="sub-options">
    <label for="main-options">Option A</label>
    <input class="option-d" type="radio" name="sub-options">
    <label for="sub-options">Option B</label>
</div>

Javascript:

$('.option-b').click(function() {
    if ($(this).is(':checked')) {
         $('.sub-options').hide();
    }
    else {
        $('.sub-options').show();
    }
});

jsFiddle: http://jsfiddle.net/VcVYM/

My goal is to be able to click option B and hide the sub-options div. But when option B isn't :checked, I want the sub options to re-appear...

I've managed to get it hidden once option-b is checked, but my else statement doesn't seem to show the sub-options div when it's not checked.

Thanks for taking a look!

D

Was it helpful?

Solution

You need to add the click handler to both radio buttons

$('.option-b, .option-a').click(function() {
    if ($('.option-b').is(':checked')) {
         $('.sub-options').hide();
    }             
    else {
        $('.sub-options').show();
    }
});

OTHER TIPS

You are not firing the click event when you're clicking on option-a, and thus it will not check if option-b is checked or not. This should work though:

$('.option-a, .option-b').click(function() {

    if ($(this).hasClass('option-a')) {

        $('.sub-options').hide();

    }
    else {
        $('.sub-options').show();
    }

});

Your event handler is attached to option-b, therefore it won't fire when option-a is clcked

$('.option-b').click(function() { $('.sub-options').hide(); } );
$('.option-a').click(function() { $('.sub-options').show(); } );

The reason it's not showing is you only call that function on the click event of option B:

$('.option-b').click(function() {

if ($(this).is(':checked')) {
     $('.sub-options').hide();
}         
else {
    $('.sub-options').show();
}

Therefore clicking on option A doesn't call anything and so sub-options never gets displayed. Every time you click on B it of course sets checked to true so that part works.

Since these are radio buttons you don't even need the check - just add a click event for option a:

$('.option-a').click(function() {

    $('.sub-options').show();

}

I have update your JS Fiddle for you. It now works. http://jsfiddle.net/VcVYM/10/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top