简体   繁体   中英

How to prevent button from submitting the form and call Javascript method (with twist)?

I don't know why it's very hard to find the answer for this simple problem. This Q/A is to help my fellow Javascript newbies like me to help understand the catch in selectively stopping the form cancellation.

I just write a very simple javascript function:

myfunc()
{
    if (conditionsatisfied) 
    {
        $("#myform").submit();
        return true;
    else 
    {
        alert ('there's a mistake on the form!');
        return false;
    }
}

which I hoped will allow the form to submit if the validation is true. if not, stop the form submit.

but, even though the validation is run correctly (the alert box is shown), the form will be still submitted. it happens whether I call the function from:

<form id="myform" action="target.php" onsubmit="myfunc();">

or

<input type="submit" onclick="myfunc();">

don't asked me to change the input type into button, because I've tried that, and for some strange reason, it causes the form to sometimes invalid on the receiver page (target.php).

the only way I can make the submit work is by put the return false on the inline javascript:

<form id="myform" action="target.php" onsubmit="myfunc(); return false;">

or

<input type="submit" onclick="myfunc(); return false;">

but that would defeat my purpose to "continue the form submission when everything is okay, and halt when it's not okay" because I can't control the return false; code. so that's the entire egg and chicken chase I've been confused for some time.

Then something occurred to me, that this is inline javascript code. Sure I can put some code on the inline code, right? When I look again at the inline code myfunc(); return false; myfunc(); return false; , the important "return" that can affect the form submission cancellation is when it happens on the inline code , not on the function. I remember my function returns boolean. so I check for the boolean, and the code is revised to this:

<input type="submit" onclick="if (myfunc()==false) return false;">

and it works! and then I look at the code again, and realized that because myfunc() already return false when the inline javascript should return false, I can further simplify the code:

<input type="submit" onclick="return myfunc();">

so after all these times, I only missing the "return" code. I hope this can helps. :)

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