Reputation: 185
<html>
<head>
<script type="text/javascript">
function hideshow(which){
if (!document.getElementById)
return
if (which.style.display=="block")
which.style.display="none"
else
which.style.display="block"
}
</script>
</head>
<body>
credit card
<a href="javascript:hideshow(document.getElementById('adiv123'))">
<input type="checkbox" />
</a>
<div id="adiv123" style="font:24px normal; style=display:block;">
check
<input type="text" name="check" class="styled"/>
</div>
</body>
</html>
The output of the program must be: it should display the text when we check the checkbox and should hide the text when checkbox was unchecked. In this case,when we open the output for the first time the text was displayed without checking the checkbox. can anyone clarify why it was happening?
Upvotes: 1
Views: 107
Reputation: 123397
This happens because you don't run the hideshow
function until you click on your checkbox (why did you wrap it into a link?). So after the pageload the adjacent div is always displayed, regardless of the state of the checkbox element.
Anyway, if you don't support IE8 and previous, you can achieve the same behaviour with css only. E.g.
html
<input type="checkbox" />
<fieldset>
<span>checked</span>
<input type="text" name="check" class="styled"/>
</fieldset>
Css
input + fieldset { display: none }
input:checked + fieldset { display: block }
Upvotes: 1
Reputation: 17927
have a look here: http://jsfiddle.net/Uhcxd/
CODE
document.getElementById("adiv123").style.display = "none";
document.getElementById("showHide").onchange = function(){
if(this.checked)
document.getElementById("adiv123").style.display = "block";
else
document.getElementById("adiv123").style.display = "none";
}
OR, based on your code: http://jsfiddle.net/Uhcxd/1/
I changed this:
<div id="adiv123" style="font:24px normal; style=display:block;">
to this
<div id="adiv123" style="font:24px normal;display:none;">
Upvotes: 0
Reputation: 21231
Well, for starters, your markup is invalid. Specifically, this:
style="font:24px normal; style=display:block;"
is wrong. I think you meant this:
style="font:24px normal; display:block;"
If you wanted the element hidden on page load, you actually wanted this:
style="font:24px normal; display:none;"
Upvotes: 0