Reputation: 37
I'm trying to hide a div based off another radio group selection. Only if the value for the first group of radio buttons equals 3 should the bottom set be shown. I just can't get it to work. What am I doing wrong here?
HTML:
<label>
<input name="Weekend" type="radio" id="Weekend_0" class="Weekend" value="1" checked="checked" />
Saturday</label>
<br />
<label>
<input type="radio" name="Weekend" value="2" class="Weekend" id="Weekend_1" />
Sunday</label>
<br />
<label>
<input name="Weekend" type="radio" id="Weekend_2" class="Weekend" value="3" />
No</label>
<br />
<div class="wrapper">
<label>
<input name="AMPM" type="radio" id="AMPM_0" value="1" checked="checked" />
AM</label>
<br />
<label>
<input type="radio" name="AMPM" value="2" id="AMPM_1" />
PM</label>
<br />
</div>
JS:
$('input:radio[name="Weekend"]').click(function() {
var $this = $(this);
if ( $this.val() == 3 ) {
$this.nextAll('.wrapper').show();
} else {
$this.nextAll('.wrapper').hide();
}
});
Thanks!
Upvotes: 0
Views: 56
Reputation: 5993
Simplified JS: http://jsfiddle.net/digitalextremist/AwYjY/92/
$('input:radio[name="Weekend"]').click(function() {
if ( $(this).val() == "3" ) { //de #1
$('.wrapper').show(); //de #2
} else {
$('.wrapper').hide(); //de #2
}
});
Notes:
.wrapper
directly, as your code is.Expanded JS: http://jsfiddle.net/digitalextremist/AwYjY/91/
$(document).ready(function () {
$('input:radio[name="Weekend"]').click(function () {
toggleAMPM($(this).val())
});
$('input:radio[name="Weekend"]').each(function (i, e) {
if ( $(e).is(':checked') ) toggleAMPM( $(e).val() )
});
});
function toggleAMPM(field) {
if (field == "3") {
$('.wrapper').show();
} else {
$('.wrapper').hide();
}
}
In my version, the expanded one, you also have the toggle functionality running on pageload, which it does not do in the simplified version! You might want to consider the second option shown.
Upvotes: 1
Reputation: 27012
The .wrapper
isn't a sibling of the radio buttons. Try this:
$this.parent().nextAll('.wrapper').show();
or
$this.parent().siblings('.wrapper').show();
And if you want to simplify:
$('input:radio[name="Weekend"]').click(function () {
var $this = $(this);
$this.parent().siblings('.wrapper').toggle($this.val() == 3);
});
Upvotes: 0