tags:

views:

23

answers:

1
<div id="formheadtop">
 <input class="checkbox" type="checkbox" /></div><div class="formbody"></div>
<div id="formheadtop">
<input class="checkbox" type="checkbox" /></div><div class="formbody"></div>
<div id="formheadtop"><input class="checkbox" type="checkbox" /></div><div class="formbody"></div>



$(function() { $('input:checkbox').live('click', function () {
if ( $(this).attr('checked') == true ) 
{
    $(this).nextAll('.formbody:first').fadeIn();
}
else
{ 
$('.formbody').fadeOut();
};
});

The Code doesn't work. I want to fade out only the next div.formbody.

+2  A: 

First we'll need to change id="formheadtop" to class="formheadtop", since IDs must be unique. Then you can use this code to fade in and out the DIVs:

jQuery

$(document).ready(function(){
  $('.formheadtop :checkbox').live('click', function() {
    if ($(this).is(':checked')) {
      $(this).parent().next('.formbody').fadeIn();
    }  else { 
      $(this).parent().next('.formbody').fadeOut();
    };
  });
});

You could shorten $(this).parent().next('.formbody') to $(this).parent().next().fadeIn(), but I put in the selector, just in case you ever want to put something in between.

HTML

<div class="formheadtop"><input class="checkbox" type="checkbox" checked="checked" /></div>
<div class="formbody">test</div>
<div class="formheadtop"><input class="checkbox" type="checkbox" checked="checked" /></div>
<div class="formbody">test</div>
<div class="formheadtop"><input class="checkbox" type="checkbox" checked="checked" /></div>
<div class="formbody">test</div>

I made the checkboxes checked by default. If not, you'll need to hide the content in the formbody tags.

Here's the code in action.

Gert G
Impressive answer - looks like a lot of work went into that, with code sample in action and all. Nice job!
kander
Thanks. It didn't take that much time. Hopefully it will be useful. :)
Gert G