Reputation: 395
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>
Upvotes: 1
Views: 13137
Reputation: 253318
If I read your question right, then I think the following would work:
$('#clickMe').toggle(
function(){
$('#textBox').show();
$('#clickMe').text('hide');
},
function(){
$('#textBox').hide();
$('#clickMe').text('show');
});
If you use the attribute for
, to define the element to which the label
'connects', and also use class-names, then this can be made more generic and useful:
$('.clickMe').toggle(
function(){
$('#' + $(this).attr('for')).show();
$(this).text('hide');
},
function(){
$('#' + $(this).attr('for')).hide();
$(this).text('show');
});
Bear in mind, though, that the label
element is used to associate information with specific input
elements, as opposed to a generic identifier for arbitrary elements. Ideally, you should use a span
, or div
, element rather than a label
for this purpose.
If you do switch to using non-label
elements, then the for
attribute shouldn't be used either, in its place I'd suggest (assuming the same connection between what's currently the label
and the div
) using a custom data-*
attribute (such as data-for
) to identify the relationship.
Note, also, in the above -final- example, the use of the class
instead of the id
selector, since an id
must be unique within the document.
Upvotes: 2
Reputation: 2481
add the code below before or after your toggle.
label = $(this);
if(label.html()=="Show"){
label.html('Hide');
}else{
label.html('Show');
}
Upvotes: 0
Reputation: 3837
Use the Toogle with callback feature: http://api.jquery.com/toggle-event/
Then you can set the text for the label in each callback.
The answer here talks about the different toggle api calls.
Upvotes: 0