简体   繁体   中英

Javascript form validation still redirects

For some reason, this code always redirects to education.php regardless of whether or not the fields are blank. I want to verify the fields have values in them, but for some reason they keep redirecting but not writing anything in the database. Any help would be greatly appreciated.

<body>
<form action="education.php" method="post" onsubmit="return validate_fields()">
<div style="text-align: right">
<ul>
First Name: <input id="first_name" name="first_name" size=25/> <br>
Last Name: <input id="last_name" name="last_name" size=25/> <br>
Email: <input id="emailaddress" name="emailaddress" size=25/> <br>
Password: <input id="user_password" name="user_password" type="password" size=25/> <br>
<center><input type="submit" name="submit" id="submit" value="Register Now"/></center>
</ul>
</div>
</form>
<script type="text/javascript">
function validate_fields()
{
    var first_name = document.getElementByID("first_name").value;
    var last_name = document.getElementById("last_name").value;
    alert(""+first_name+" "+last_name);
    if (first_name.length < 1 || last_name.length < 1)
    {
        alert("Please fill in your name.");
        return false;
    }
    var email = document.getElementById("emailaddress").value;
    if (email.length < 1)
    {
        alert("Please fill in your email address.");
        return false;
    }
    var password = document.getElementById("password").value;
    if (email.length < 1)
    {
        alert("Please put in a password.");
        return false;
    }
    alert(first_name+" "+last_name+" "+email);
    return false; //was true, changed to see if still redirects.
}
</script>
</body>

You've got a typo on the first line of your function so it isn't returning false (or true), it is just not running at all. This explains both why you don't get any of the alerts and why the form submit goes ahead.

var first_name = document.getElementByID("first_name").value;
// you need a lowercase "d" here ------^

It should be .getElementById() , not .getElementByID() .

This is the sort of thing you can easily find for yourself with the appropriate developer tools for your browser. Chrome has this built in (just press ctrl-shift-J to bring up dev tools), or you can add Firebug for FireFox, and IE has had a dev toolbar option for several versions now.

You have a typo here:

var first_name = document.getElementById("first_name").value;

You wrote ByID it sould be ById !

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