Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript code returns false, but still the form is submittted

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!

like image 483
Bifterss Avatar asked Jun 20 '11 14:06

Bifterss


People also ask

How do I stop form submit if validation fails?

Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.

How do I return false on form submit?

If return value is false, then set event's canceled flag. So, in short, return false will cancel the event (or in this case, cancels the form submission).

What does return false do in JavaScript?

You use return false to prevent something from happening. So if you have a script running on submit then return false will prevent the submit from working.


1 Answers

You need to have return false; in the function called by the onclick, in this case formvalidation.

Having some function called by the "root" function return false has no effect whatsoever. The return value is lost.

like image 93
Shadow Wizard Hates Omicron Avatar answered Nov 09 '22 02:11

Shadow Wizard Hates Omicron