0
votes

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?

4

4 Answers

5
votes

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).

0
votes

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

  1. Hide all divs with id begining in "my_radio_"
  2. Show the current DIV as you are doing now
0
votes

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();
});
0
votes

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
});