Jemes
Jemes

Reputation: 407

jQuery Radio Button Show/Hide

I'm trying to use radio buttons to show and hide a div but can't get the below to work, any help would be great?

    $('input:radio[name="option"]').click(function() {
    if ( $(this).val() == "pop" ) {
        $(this).parent().next('.wrapper').show();
    } else {
        $(this).parent().next('.wrapper').hide();
    }
});

<input name="option" type="radio">
<input name="option" type="radio" value="pop">

<div class="wrapper">text</div>

Upvotes: 0

Views: 3619

Answers (3)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382464

Remove the parent(), as the .wrapper element is at the same level than the input.

You also want nextAll, not next, because next only selects the immediately following sibbling.

Working code :

$('input:radio[name="option"]').click(function() {
    var $this = $(this);
    if ( $this.val() == "pop" ) {
        $this.nextAll('.wrapper').show();
    } else {
        $this.nextAll('.wrapper').hide();
    }
});

Demonstration

If you want only the first following .wrapper element, then you may use this :

$('input:radio[name="option"]').click(function() {
    var $this = $(this), $wrapper = $this.nextAll('.wrapper').eq(0);
    if ( $this.val() == "pop" ) {
        $wrapper.show();
    } else {
        $wrapper.hide();
    }
});

Upvotes: 3

Mikee
Mikee

Reputation: 646

Try this:

$(document).ready(function(){  
    $("input[value='pop']").on("click", function() {
        $(".wrapper").toggle();
    });
});

Upvotes: 0

BryanH
BryanH

Reputation: 6062

Your .parent().next('wrapper'). has nothing to grab on to (there is no such element).

This will work

$('.wrapper').show();

Upvotes: 0

Related Questions