Home > Software design >  How do I prevent form fields from clearing out?
How do I prevent form fields from clearing out?

Time:10-05

I have a form in an HTML page with a script that checks the fields in the form, the problem is that whenever I write something "wrong" in the field and the script gives an alert(), all the fields of the form clear out.

Here's the code:

<html>
    <head>
        <title>Login</title>
        <link rel="stylesheet" href="style.css">
        <link rel="icon" href="loginIcon.png">
        <script src="script.js"></script>
    </head>
    <body>
        <form id="form" method="POST">
            <div class="center"><input type="text" placeholder="E-mail" id="email" name="email"></div>
            <div class="center"><input type="password" placeholder="Password" id="pass" name="pass"></div>
            <div><input type="checkbox" class="check" id="check"> I'm not a Robot</div>
            <div class="center"><button onclick="check()">LOGIN</button></div>
            <a href="#">Don't have an account yet? Sign Up</a>
        </form>
    </body>
</html>

And the script:

function check() {
    var em = document.getElementById("email").value.trim()
    var ps = document.getElementById("pass").value.trim()
    var ch = document.getElementById("check")

    if (ch.checked) {
        if (em == "" || em == undefined) {
            alert("Email missing")
            return false
        } else if (ps == "" || ps == undefined) {
            alert("Password missing")
            return false
        } else {
            if (!em.includes("@")) {
                alert("Missing '@'")
                return false
            } else if (ps.length > 16) {
                alert("Password must be 16 characters or less")
                return false
            } else {
                document.getElementById("form").action = "check.php"
            }
        }
    } else {
        alert("You're a Robot!")
        return false
    }
}

CodePudding user response:

Change your form to this

<form id="form" action="check.php" method="POST" onsubmit="return check()">
            <div class="center"><input type="text" placeholder="E-mail" id="email" name="email"></div>
            <div class="center"><input type="password" placeholder="Password" id="pass" name="pass"></div>
            <div><input type="checkbox" class="check" id="check"> I'm not a Robot</div>
            <div class="center"><button type="submit">LOGIN</button></div>
            <a href="#">Don't have an account yet? Sign Up</a>
        </form>

Right now, the form is submitted after the alert, you need to have this event on form submission so that in case of false, form submission is halted.

onsubmit receives a boolean (true by default) so if you return false from the function, the submission will be halted (as done here).

  • Related