简体   繁体   中英

Don't know why I am getting an alert! 'undefined' message

I am learning PHP, JavaScript. The code that follows comes from a textbook that I am using.

<script>
function validate(form)
    {
    fail  = validateForename(form.forename.value)
    fail += validateSurname(form.surname.value)
    fail += validateUsername(form.username.value)
    fail += validatePassword(form.password.value)
    fail += validateAge(form.age.value)
    fail += validateEmail(form.email.value)

    if   (fail == "") return true
    else { alert(fail); return false } 
    }
<body>

<table border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee">
    <th colspan="2" align="center">Signup Form</th>
    <form method="post" action="adduser387.php" onSubmit="return      validate(this)">
<tr><td>Forename</td> ....

The validate functions work. When all fields are validated and I 'submit', the logic falls through to 'else { alert(fail); return false }' giving me an 'undefined' message - not sure why. Please let me know if I provided insufficient info. I could not find an answer on the Internet. Thanks.

Your js function has to be like this:

function validate(form) {
        var fail = '';
        fail += validateForename(form.forename.value);
        fail += validateSurname(form.surname.value);
        fail += validateUsername(form.username.value);
        fail += validatePassword(form.password.value);
        fail += validateAge(form.age.value);
        fail += validateEmail(form.email.value);

        if (fail == "") {
            return true;
        }
        else {
            alert(fail);
            return false
        }
    }

Problem with your script is fail is not defined anywhere hence its value is undefined (not considering your filed validation functions return value), hence value if fail == "" will never be true as undefined is not equals to '' and thats why your else condition is getting satisfied. As there is undefined value in fail , you are getting alert as undefined

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