JavaScript code returns false, but still the form is submittted

Viewed 27706

I have a form with JavaScript validation. Upon there being an error, the submit button should 'grey-out' and the form should not be submitted. However, the last couple of functions seem to submit the form even though they pop the alert box. Why?

Button code:

<input type="submit" name="button" id="button"
       onclick='return formvalidation();' value="Next" />

Non-working function example:

function BlankSite() {
    var SiteNum= document.getElementsByName("sitesinput")[0].value;
    if ((SiteNum == "") || (SiteNum == 0))
    {
        alert("You have not selected an amount of sites.")
        document.forms[0].button.disabled = true;
        return false;
    }
}

Function initiator:

function formvalidation()
{
    ZeroPhones();
    BlankPC();
    BlankSite();
    BlankSeats();
    phone_change();
} // End of formvalidation

This is very strange and I have tried various workarounds all to no avail!

6 Answers

My solution to this problem was to disable the submit button until the validation was successful. Something along these lines:

function checkPassword() {
    // This is my submit button

    document.getElementById('nextBtn').setAttribute('disabled', 'disabled');

    password1 = document.getElementsByName("pwd1")[0].value;
    password2 = document.getElementsByName("pwd2")[0].value;

    if (password1 == '') {
        // If password not entered
        alert ("Please enter Password");
        return false;
    } else if (password2 == ''){
        // If confirmation password not entered
        alert ("Please enter confirm password");
        return false;
    } else if (password1 != password2) {
        // If NOT the same, return false.
        alert ("\nPassword did not match: Please try again...");
        return false;
    } else {
        document.getElementById('nextBtn').removeAttribute('disabled');
        return true;
    }
}
Related