Reputation: 319
I have searched and searched over so many previously answered questions and to my surprise, NONE of them answer what I am trying to accomplish. with JQuery this is easy but I am struggling with strict javascript.
I cannot have any embedded JS OR CSS in the html...
This is what I have so far:
function showhide()
{
var billingaddress = document.getElementById("billingaddress");
if (billingaddress.style.display === "block")
{
billingaddress.style.display = "none";
}
else if (billingaddress.style.display === "none")
{
billingaddress.style.display = "block";
}
}
function init ()
{
var billingcheckbox = document.getElementById("billing");
if (billingcheckbox.checked)
{
showhide();
}
else
{
showhide();
}
It is hidden by default using CSS.
Cheers,
Upvotes: 1
Views: 139
Reputation: 11
The code below should do it -- but to be sure make sure all your IDs are matching up with what is in the HTML markup:
function showhide(show) {
var billingaddress = document.getElementById("billingaddress");
if (show) {
billingaddress.style.display = "block";
} else {
billingaddress.style.display = "none";
}
}
function init () {
var billingcheckbox = document.getElementById("billing");
if (billingcheckbox.checked) {
showhide(true);
} else {
showhide(false);
}
}
Upvotes: 0
Reputation: 938
It's as easy as this:
this keyword inside event handler references checkbox element so you can get checkbox state with this.checked property.
<input type="checkbox" id="billing">
<input type="text" id="billingaddress" placeholder="Address" style="display:none">
<script>
var billingAddress = document.getElementById("billingaddress");
var billingCheckbox = document.getElementById("billing");
billingCheckbox.addEventListener('click', function(event) {
billingAddress.style.display = this.checked ? "block" : "none";
})
</script>
Upvotes: 1
Reputation: 4691
With he code you've provided, it can be done like this.
billingaddress.style.display
is empty by default, you can easily check it in the if without a comparison.
function showhide() {
if (billingaddress.style.display) billingaddress.style.display = ""
else billingaddress.style.display = 'none';
}
var billingaddress = document.getElementById("billingaddress")
var billingcheckbox = document.getElementById("billing")
billingcheckbox.addEventListener('change', showhide)
billingcheckbox.checked = true
showhide()
<input type="checkbox" id="billing"/> Hide
<div id="billingaddress">Lorem Ipsum</div>
Upvotes: 1