How to use jQuery to show/hide divs based on radio button selection?
I have some radio buttons and I'd like to have different hidden divs show up based on which radio button is selected. Here's what the HTML looks like:
<form name="form1" id="my_form" method="post" action="">
<div><label><input type="radio" name="group1" value="opt1">opt1</label></div>
<div><label><input type="radio" name="group1" value="opt2">opt2</label></div>
<div><label><input type="radio" name="group1" value="opt3">opt3</label></div>
<input type="submit" value="Submit">
</form>
....
<style type="text/css">
.desc { display: none; }
</style>
....
<div id="opt1" class="desc">lorem ipsum dolor</div>
<div id="opt2" class="desc">consectetur adipisicing</div>
<div id="opt3" class="desc">sed do eiusmod tempor</div>
And here's my jQuery:
$(document).ready(function(){
$("input[name$='group2']").click(function() {
var test = $(this).val();
$("#"+test).show();
});
});
The reason I'm doing it that way is because my radio buttons and divs are being generated dynamically (the value of the radio button will always have a corresponding div). The code above works partially - the divs will show when the correct button is checked, but I need to add in some code to make the divs hide again once the button is unchecked. Thanks!
Update 2015/06
As jQuery has evolved since the question was posted, the recommended approach now is using $.on
$(document).ready(function() {
$("input[name=group2]").on( "change", function() {
var test = $(this).val();
$(".desc").hide();
$("#"+test).show();
} );
});
or outside $.ready()
$(document).on( "change", "input[name=group2]", function() { ... } );
Original answer
You should use .change()
event handler:
$(document).ready(function(){
$("input[name=group2]").change(function() {
var test = $(this).val();
$(".desc").hide();
$("#"+test).show();
});
});
should work
Just hide them before showing them:
$(document).ready(function(){
$("input[name$='group2']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#"+test).show();
});
});
$(document).ready(function(){
$("input[name=group1]").change(function() {
var test = $(this).val();
$(".desc").hide();
$("#"+test).show();
});
});
It's correct input[name=group1]
in this example. However, thanks for the code!