Reputation: 20346
I have three radio buttons and a div after each one like this:
<input type="radio" name="radios" id="my_radio_1" value="" />
<div id="my_radio_1_text" style="display:none;">Content for radio 1</div>
<input type="radio" name="radios" id="my_radio_2" value="" />
<div id="my_radio_2_text" style="display:none;">Content for radio 2</div>
<input type="radio" name="radios" id="my_radio_3" value="" />
<div id="my_radio_3_text" style="display:none;">Content for radio 3</div>
As you can see, the divs are initially hidden with display:none;
. What I'm trying to do is to show the div right after each radio button when it is selected (and if a radio button is not selected, I want to hide the div after it). I can show the div after a radio button when it is selected by doing this:
$(document).on('change', 'input:radio[name=radios]', function(){
$('#' + $(this).attr('id') + '_text').show();
});
But I don't know how to hide the div when another radio button is selected. Any ideas please?
Upvotes: 0
Views: 3302
Reputation: 10880
Like this
$(document).on('change', 'input:radio[name=radios]', function () {
$('input:radio[name=radios]').next().hide(); // hide all divs after radio
$(this).next().show(); // show the div next to current radio button
});
Upvotes: 0
Reputation: 3127
What I do is hide all the divs
before showing the one that is selected. Give your divs a class of myDiv
, and hide them using javascript before showing them:
$(document).on('change', 'input:radio[name=radios]', function(){
$('.myDiv').hide();
$('#' + $(this).attr('id') + '_text').show();
});
Upvotes: 0
Reputation: 66663
You can do the following when a radio is clicked.
$(document).on('change', 'input:radio[name=radios]', function(){
$('div[id^="my_radio_"]').hide(); // hide all DIVs begining with "my_radio_"
$('#' + $(this).attr('id') + '_text').show(); // show the current one
});
Explanation
Upvotes: 0
Reputation: 382150
Simply hide them all before showing the new one :
$(document).on('change', 'input:radio[name=radios]', function(){
$('div[id$="_text"]').hide(); // hide all divs whose id ends in _text
$('#' + this.id. + '_text').show();
});
If you don't like the idea of hiding and then showing, you could also use
$('div[id$="_text"]').not('#' + this.id. + '_text').hide();
$('#' + this.id. + '_text').show();
but there's no reason to bother (the screen isn't rendered until your event handler ends).
Upvotes: 5