tags:

views:

813

answers:

2

I want to enhance some fieldsets with the option to show / hide their contents upon clicking their label.

Currently, the HTML looks like this:

<fieldset>
    <legend>Fieldset 1</legend>
    <!-- Some input, p, div, whatever -->
</fieldset>
<fieldset>
    <legend>Fieldset 2</legend>
    <!-- Some input, p, div, whatever -->
</fieldset>

So, on click of one fieldset legend, anything but the clicked legend of the parent fieldset should be toggled.

I tried using this:

$("fieldset *:not(legend)").hide();
$("fieldset legend").click(function(){
    $(this).nextAll().slideToggle();
});

But it doesn't do anything (not even hide the contents in the first place). Of course I want to only toggle the view on the very fieldset the user has clicked, so it has to somehow determine what legend was clicked and then hide the contents of the corresponding fieldsets.

Sure, I could give them all IDs and write the code for every fieldset, but thats rather redundant seeing it would always be the same I think there has to be a way to make this functionality universal for any amount of fieldsets...

Anyone has a neat idea?

+2  A: 

If I was you I'd wrap content of fieldset in div, and to it like that:

<script type="text/javascript">
     $(function(){
      $('legend').click(function(){
       $(this).parent().find('.content').slideToggle("slow");
      });
     });
</script>

<fieldset>
    <legend>Fieldset 1</legend>
    <!-- Some input, p, div, whatever -->
    <div class="content">
     this<br />
     is<br />
     content<br />
    </div>
</fieldset>
<fieldset>
    <legend>Fieldset 2</legend>
    <!-- Some input, p, div, whatever -->
    <div class="content">
     this<br />
     is<br />
     content<br />
    </div>
</fieldset>

So now when you click on the label it will slide the content up/down and leave your label visible.

rochal
Yeah, well thats one way to do it of course and it will work, still it's a hack and requires the HTML to be edited :-/ Still, thanks.
ApoY2k
How is doing this a hack?... you didn't specify that you didn't want to modify the HTML.
fudgey
A: 
$(function(){
  $('legend').click(function(){
   $(this).siblings().slideToggle("slow");
  });
});

This works. It's the same concept really, just the inverse.

creativetim