Home > OS >  JavaScript will not change display to "none"
JavaScript will not change display to "none"

Time:11-24

I am trying to add a click event handler to a button that will cause it to change the CSS display property of a sign-in form to 'none'.

The JS:

// make the form disappear when the user clicks initSignUpBtn
const initSignUpBtn = document.querySelector(".btn signup-btn");
initSignUpBtn.addEventListener("click", () =>{
    document.getElementById("signinForm").style.display="none";
});

The HTML:

<form  id="signinForm">
    <div >
        <input type="email"  id="emailInput" placeholder="Email or username">
    </div>
    <div >
        <input type="password"  id="passwordInput" placeholder="Password">
    </div>
    <div >
        <label >
            <input  type="checkbox"> Remember me<a  href="#">Need Help?</a>
        </label>
    </div>
    <button type="button"  id="signinbtn">Sign in</button>
    <button type="button"  id="initSignUpBtn">New? Sign up!</button>

</form>

I added an event listener of type 'click' to the button, and wrote an anonymous function that changes the display property of the form to 'none' but this did not work.

CodePudding user response:

Your querySelector is incorrect. Why not use document.getElementById("initSignUpBtn") since you have an ID on it? If you do want to use querySelector, it should be document.querySelector(".btn.signup-btn") or document.querySelector(".signup-btn").

CodePudding user response:

you can try this logic :

<form  id="signinForm">
    <div >
        <input type="email"  id="emailInput" placeholder="Email or username">
    </div>
    <div >
        <input type="password"  id="passwordInput" placeholder="Password">
    </div>
    <div >
        <label >
            <input  type="checkbox"> Remember me<a  href="#">Need Help?</a>
        </label>
    </div>
    <button type="button"  id="signinbtn">Sign in</button>
    <button type="button"  id="initSignUpBtn">New? Sign up!</button>

</form>

const initSignUpBtn = document.querySelector(".btn.signup-btn");
initSignUpBtn.addEventListener("click", () =>{
    document.getElementById("signinForm").style.display="none";
});
<form  id="signinForm">
    <div >
        <input type="email"  id="emailInput" placeholder="Email or username">
    </div>
    <div >
        <input type="password"  id="passwordInput" placeholder="Password">
    </div>
    <div >
        <label >
            <input  type="checkbox"> Remember me<a  href="#">Need Help?</a>
        </label>
    </div>
    <button type="button"  id="signinbtn">Sign in</button>
    <button type="button"  id="initSignUpBtn">New? Sign up!</button>

</form>

  • Related