1

I have a site that is covered by a div. I want to make the div disappear when someone enters the correct password. I validate the form with Javascript and successfully change the CSS of that div from display:block to display:none, but immediately after the display property has been changed it changes back to default again. I want to have it so the display of #overlay is forever set to none if the password is correct.

The form.

<form id="overlay-form" name="overlay-form" method="post" onsubmit="validateForm();">
<input id="overlay-password" name="overlay-password" type="password">
<input type="submit" id="overlay-submit" value="Submit">
</form> 

Javascript.

<script>
    function validateForm() {
        var x = document.forms["overlay-form"]["overlay-password"].value;
            if (x == "password") {
                document.getElementById('overlay').style.display = "none";
            }
    }
</script>
1
  • 1
    Do you want the page to refresh or..? In this way, the page will reload due to the form submit... The form is coming back to the initial state because you actually are refreshing the page by submitting the form, I think you don't want to submit it, but you just want to use a regular button. jsfiddle.net/zth0vkzo <-- This is what you're looking for, in my opinion. Commented Dec 24, 2014 at 11:45

2 Answers 2

2

By default, a form submit does a reload of the page (or redirects to the action url if given). If you want to prevent this default behaviour, add this to your javascript:

function validateForm(event) { // pass in the event as a parameter, this is the form submit

    var x = document.forms["overlay-form"]["overlay-password"].value;
        if (x == "password") {
            document.getElementById('overlay').style.display = "none";
            event.preventDefault(); // prevent the default behaviour here
        }
}
Sign up to request clarification or add additional context in comments.

Comments

0

When you press the submit button, the page reloads, and the div is visible again. You need a regular button, not a submit button. <input type="button"> makes a normal button that doesn't submit the form.

You must not write the password to the javascript, because everyone can see it!

3 Comments

But if i don't submit the form how will I be able to validate the form?
And i'm using Javascript for now because it it easy to change css with js
Remove onsubmit="validateForm();" from the form tag, and add onclick="validateForm();" to the button.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.