How can I get the label to toggle show/hide? Below is my code and currently it is also displaying show. I would like it to toggle from show to hide and from hide back to show. when show is displayed the div will be hidden but when show is clicked the label will switch to hide and the div will be displayed and when hide is clicked the label will go back to show and the div will be hidden
<html>
<head>
<title>jQuery test page</title>
<script type="text/javascript" src="../scripts/jquery-1.4.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#clickMe").click(function() {
$("#textBox").toggle();
});
});
</script>
</head>
<body>
<label id="clickMe">Show</label>
<br />
<div id="textBox" style="display: none">This text will be toggled</div>
</body>
</html>
If I read your question right, then I think the following would work:
JS Fiddle demo.
If you use the attribute
for, to define the element to which thelabel‘connects’, and also use class-names, then this can be made more generic and useful:JS Fiddle demo.
Bear in mind, though, that the
labelelement is used to associate information with specificinputelements, as opposed to a generic identifier for arbitrary elements. Ideally, you should use aspan, ordiv, element rather than alabelfor this purpose.If you do switch to using non-
labelelements, then theforattribute shouldn’t be used either, in its place I’d suggest (assuming the same connection between what’s currently thelabeland thediv) using a customdata-*attribute (such asdata-for) to identify the relationship.Note, also, in the above -final- example, the use of the
classinstead of theidselector, since anidmust be unique within the document.