views:

1169

answers:

2

Hello, 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!

+2  A: 

You should use .change() event handler:

$(document).ready(function(){ 
    $("input[name=group2]").change(function() {
        var test = $(this).val();
        $(".desc").hide();
        $("#"+test).show();
    }); 
});

should work

Zlatev
A: 

Just hide them before showing them:

$(document).ready(function(){ 
    $("input[name$='group2']").click(function() {
        var test = $(this).val();
        $("div.desc").hide();
        $("#"+test).show();
    }); 
});
AlbertEin
thanks, that's exactly what I needed
Manoj