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?
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.
$(function(){
$('legend').click(function(){
$(this).siblings().slideToggle("slow");
});
});
This works. It's the same concept really, just the inverse.
Extended version
HTML (legend contains [-] span):
<fieldset>
<legend>My Area <span>[-]</span></legend>
Content of fieldset...
</fieldset>
JavaScript (requires jQuery):
$(function(){
// Set cursor to pointer and add click function
$("legend").css("cursor","pointer").click(function(){
var legend = $(this);
var value = $(this).children("span").html();
if(value=="[-]")
value="[+]";
else
value="[-]";
$(this).siblings().slideToggle("slow", function() { legend.children("span").html(value); } );
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With