Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 691
M Thomas Avatar asked May 05 '10 22:05

M Thomas


People also ask

How can I show and hide elements based on selected option with jQuery?

If you want to hide/show div on dropdown selected, use the jQuery hide() and show(). Before you perform hide or show div on dropdown selection, you need to hide them first using CSS display:none.

How do you do show hide in jQuery?

Syntax: $(selector). hide(speed,callback);


1 Answers

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

like image 74
Z. Zlatev Avatar answered Sep 30 '22 18:09

Z. Zlatev