Reputation: 2397
I have multiple sets of yes/no radio buttons that hide or show divs based on the radio value. How do I select ONLY the CLOSEST divs to the set of radio buttons that are changed?
http://jsfiddle.net/infatti/esLMh/
This works but changes all divs on the page instead of only the closest.
$('.hide-show input').change(function() {
$('.hide-show-yes').toggle(this.value == 'yes');
$('.hide-show-no').toggle(this.value == 'no');
});
$('.hide-show input:checked').change(); //trigger correct state onload
How do I only effect the closest divs to the radio set when there are multiple sets on a page?
$('.hide-show input').change(function() {
$(this).next('.hide-show-yes').toggle(this.value == 'yes').next('hide-show-no').toggle(this.value == 'no');
});
$('.hide-show input:checked').change(); //trigger correct state onload
Upvotes: 0
Views: 838
Reputation: 148110
You need to access the next element of parent div of radio button, You can do it this way
$('.hide-show input').change(function() {
$(this).closest('div').next('.hide-show-yes').toggle(this.value == 'yes');
$(this).closest('div').next('.hide-show-no').toggle(this.value == 'no');
});
$('.hide-show input:checked').change(); //trigger correct state onload
Upvotes: 2
Reputation: 837
$('.hide-show input').change(function() {
$(this).parent().next().toggle(this.value == 'yes');
$(this).parent().next().next().toggle(this.value == 'no');
});
$('.hide-show input:checked').change(); //trigger correct state onload
Upvotes: 0
Reputation: 4967
Give your input fields an id, you can control the ids so you can do something like
$('#radioButtonOne').change(function() {
and
$('#radioButtonTwo').change(function() {
That way you can always be sure to know what is being changed, and you do different function corresponding to the changes.
I also recommend having only ONE div for each state, so you change the text of the div instead of hiding and showing multiple divs.
I also recommend using the on jquery function, so that you can change the DOM but still be able to listen to NEW elements that you might create.
$("#radioButtonOne").on("change", function(event){
Upvotes: 0