...

View Full Version : show/hide text or div



wasssu
03-22-2009, 06:53 PM
I have this code that show/hide a div:

<html>
<head>
<script type="text/javascript">
function showHide()
{
if(document.getElementById('Checkbox1').checked)
{
document.getElementById('Text1').style.visibility = 'hidden';
}
else
{
document.getElementById('Text1').style.visibility = 'visible';
}
}
</script>

</head>
<body>

<input id="Checkbox1" type="checkbox" onclick="showHide();" /> Show/Hide

<div id="Text1">
Textul meu...
</div>

</body>
</html>

If a have 10 DIVs (every div with a checkbox) how can i hide divs withought writing 10 times the function, one function for every ID? How can i pass to the function the id of the div that i check? (or other idea)

thanks.

hotwheelharry
03-22-2009, 07:15 PM
this should do the trick.
call the showHide function from an onclick event and pass in the element that you want to show/hide as a parameter.




<html>
<head>
<script type="text/javascript">
function showHide(element)
{
if(element)
{
if(this.checked)
{
element.style.visibility = 'hidden';
}
else
{
element.style.visibility = 'visible';
}
}
else
{
//handle no element passed in if you want to here
}
}
</script>

</head>
<body>

<input id="Checkbox1" type="checkbox" onclick="showHide(document.getElementById('Text1'));" /> Show/Hide Text1
<input id="Checkbox2" type="checkbox" onclick="showHide(document.getElementById('Text2'));" /> Show/Hide Text2

<div id="Text1">
Textul meu...
</div>
<div id="Text2">
Textul meu...(number 2)
</div>

</body>
</html>

wasssu
03-22-2009, 09:20 PM
[QUOTE=hotwheelharry;796531]this should do the trick.
call the showHide function from an onclick event and pass in the element that you want to show/hide as a parameter.

this should do the trick but... it doesn't work :( ... please try it

wasssu
03-22-2009, 09:46 PM
problem solved.. thanks

Old Pedant
03-22-2009, 10:01 PM
Variations on that theme, to keep it simpler:


<script type="text/javascript">
function showHide(cb)
{
var dv = document.getElementById("Text" + cb.name.substring(2) );
if ( dv ) dv.style.display = ( cb.checked ? "block" : "none" );
}
</script>

....

<input name="CB1" type="checkbox" onclick="showHide(this);" > Show/Hide Text1
<input name="CB2" type="checkbox" onclick="showHide(this);" > Show/Hide Text2

....

<div id="Text1" style="display: none;">.. whatever...</div>
<div id="Text2" style="display: none;">...stuff ...</div>

Using display:none is better in many cases than visiblity:hidden, because even hidden elements use up "space" on the screen.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum