Search code examples
htmljqueryradio-button

jquery - showing div based on radio button checked?


First of all, I searched here for the past hour to see if I found an answer to my question before I posted, but you're my last hope! I found a piece of code that nearly works as I want it, but not quite.

  • I need to get rid of the fade-in and fade-out.
  • I need the script to check onload which radio button is checked and show the correct div.

Here is my code:

 <input type="radio" name="d_method" class="c_email"/>Email   
 <input name="d_method" type="radio" class="c_collection"/>Colletion 
 <input name="d_method" type="radio" class="c_post"/>Post

 <div id="c_email" style="display:none;">
   email textbox
 </div>
 <div id="c_collection" style="display:none;">
   collection textbox
 </div>
 <div id="c_post" style="display:none;">
   post textbox
 </div>

And here is the jquery:

 $(':radio').change(function() {
     var itemSelector = '#' + $(this).attr('class');
     $('div').stop().fadeOut(function() {
         $(itemSelector).fadeIn();
     });
 });

Solution

  • Try this

    $(function(){
        $(':radio').click(function() {
            $('#' + $(this).attr('class')).fadeIn().siblings('div').hide();
        })
        .filter(':checked').click();//trigger the click event
    });​
    

    Working demo - http://jsfiddle.net/H8VVP/1/