0

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>
Jemes
  • 407
  • 1
  • 10
  • 27
  • Please update your HTML to show the parent, and another set of radios and `class="wrapper"` tags. As it is, what you have here isn't enough to show what you're trying to do. – BryanH Feb 05 '13 at 15:57
  • Duplicate of http://stackoverflow.com/questions/2777139 ? – BryanH Feb 05 '13 at 15:59

3 Answers3

3

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();
    }
});
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • I need the parent tag as I have this form repeated a few times on the page and I don't want all the wrapper classes to close. – Jemes Feb 05 '13 at 15:54
0

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

This will work

$('.wrapper').show();
BryanH
  • 5,826
  • 3
  • 34
  • 47
0

Try this:

$(document).ready(function(){  
    $("input[value='pop']").on("click", function() {
        $(".wrapper").toggle();
    });
});
Mikee
  • 626
  • 1
  • 10
  • 23