How to use jQuery to show/hide divs based on radio button selection?

Posted by manoj382 on Stack Overflow See other posts from Stack Overflow or by manoj382
Published on 2010-05-05T22:09:58Z Indexed on 2010/05/05 22:18 UTC
Read the original article Hit count: 291

Filed under:
|
|
|

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!

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about radio