简体   繁体   中英

Hide and Show DIV using strict javascript with no embedded JS or CSS

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,

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> 

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> 

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM