I know from scouring the Web that this is a very common Javascript question, but I have a twist on the question which is giving me headaches, and I hope some of the brilliant minds here at DaniWeb can help show me the error of my ways.
Say a user has checked a checkbox when submitting a form. I have a PHP script that records that check in a MySQL record. Later when they visit the page, the PHP script shows the checkbox as being checked. That's all working fine.
Now here's what I'm TRYING to do: Since the checkbox is checked when the page loads, I want a certain div to show up. And when the user UNchecks the checkbox, I want the div to go away. Simple, right?
Here's the Javascript I've placed in the header:
function Toggle(id) {
if (document.getElementById(id).style.display == "none" || document.getElementById(id).style.display == "") {
document.getElementById(id).style.display = "block";
} else if (document.getElementById(id).style.display == "block") {
document.getElementById(id).style.display = "none";
} else {
document.getElementById(id).style.display = "none";
}
}
In the CSS, I've styled a div thusly:
#test01 { width:200px; padding:15px; background-color:#ffc; display:block; }
And here's what I'm doing in the <body>:
<input type="checkbox" name="" onclick="Toggle('test01')" checked="checked" /> Yellow Box<br />
<div id="test01">
This should show up when you click Yellow Box. And it should go away when you click it again.
</div>
When I uncheck the checkbox (first click), nothing happens: the div still shows up.
Then when I re-check the checkbox (second click), the div goes away.
And then when I un-check the checkbox again (third click), the div comes back.
In other words, it's doing the OPPOSITE of what I want.
It seems that when I click the checkbox the first time (to uncheck it), the Javascript pulls an empty value. Only with the second click is it finding a value ('none').
Can anyone please tell me what I'm doing wrong? Thank you!