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?
Denys Séguret :
Simply hide them all before showing the new one :\n\n$(document).on('change', 'input:radio[name=radios]', function(){\n $('div[id$=\"_text\"]').hide(); // hide all divs whose id ends in _text\n $('#' + this.id. + '_text').show();\n});\n\n\nIf you don't like the idea of hiding and then showing, you could also use\n\n$('div[id$=\"_text\"]').not('#' + this.id. + '_text').hide();\n$('#' + this.id. + '_text').show();\n\n\nbut there's no reason to bother (the screen isn't rendered until your event handler ends).",
2013-06-27T13:24:44
techfoobar :
You can do the following when a radio is clicked.\n\n$(document).on('change', 'input:radio[name=radios]', function(){\n $('div[id^=\"my_radio_\"]').hide(); // hide all DIVs begining with \"my_radio_\"\n $('#' + $(this).attr('id') + '_text').show(); // show the current one\n});\n\n\nExplanation\n\n\nHide all divs with id begining in \"my_radio_\"\nShow the current DIV as you are doing now\n",
2013-06-27T13:25:08
dKen :
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:\n\n$(document).on('change', 'input:radio[name=radios]', function(){\n $('.myDiv').hide();\n $('#' + $(this).attr('id') + '_text').show();\n});\n",
2013-06-27T13:26:02