onsubmit method doesn't stop submit
Asked Answered
A

6

9

My onsubmit is not working. My idea was to put some mandatory fields and, in order to achieve that, I was using the onsubmit method inside a form in HTML that called a JavaScript function.

The idea was if all the mandatory fields were filled, the javascript function would return true and it would move on to page /control/Cadastro.php. Otherwise, if any mandatory field was empty, it would return false and it wouldn't move to page /control/Cadastro.php, staying in the current page until true.

Unfortunately, the function does return false if all the mandatory fields are not filled, as expected, but it still moves to page /control/Cadastro.php, even if it shouldn't.

I'm going to cut off some code to make my point of view perceptible.

<!DOCTYPE html>
<html>
    <head>
        <script>
            function ValidateRequiredFields()
            {
                var message = new String('\nCampos obrigatórios:\n');
                var flag=new Boolean(1);
                var x=document.forms["theForm"]["nr_processoCA"].value;
                if (x==null || x==""){
                    message += '\nNº do processo\n'; 
                    flag = new Boolean(0);
                } 
                if (flag == false){
                    alert(message);
                }
                return flag;    
            }
        </script>
    </head>
    <body>
        <form name="theForm" onsubmit="return ValidateRequiredFields()" method="post" action="../control/Cadastro.php"> 
            Nº do Processo: <br>
            <input type="text" name="nr_processoCA" class="input-xlarge">
            <br>
            <div class="row-fluid" style="text-align:center;">
                <input type="submit" class="btn btn-primary btn-large" value="Gravar">
            </div>   
         </form>
    </body>
</html>
Airdry answered 27/9, 2012 at 14:3 Comment(1)
Don't be so verbose, just write var flag = true or flag = false, idem for String :)Chadwickchae
B
13

You should use preventDefault inside your onsubmit function. I modified your code:

function ValidateRequiredFields()
{
    var message = new String('\nCampos obrigatórios:\n');
    var flag=new Boolean(1);


    var x=document.forms["theForm"]["nr_processoCA"].value;
    if (x==null || x==""){
        message += '\nNº do processo\n'; 
        flag = new Boolean(0);
    }

    if (flag == false){
        if(event.preventDefault){
            event.preventDefault();
        }else{
            event.returnValue = false; // for IE as dont support preventDefault;
        }
        alert(message);
    }

    return flag;
}

DEMO

Boehmer answered 27/9, 2012 at 14:15 Comment(0)
C
3

To make this work, your ValidateRequiredFields function needs to return a boolean value. And then you should attach that method to the onSubmit event. Remember, that for onsubmit you need to use the return keyword.

This code sample works:

<!DOCTYPE html>
<html>
<head>
<script>
    function ValidateRequiredFields() {
        var message = new String('\nCampos obrigatórios:\n');
        var flag=1;

        var x=document.forms["theForm"]["nr_processoCA"].value;
        if (x==null || x==""){
            message += '\nNº do processo\n'; 
           alert(message);
           return false;
        }
        return true;
    }
</script>
</head>

<body>

<form name="theForm" method="post" action="../control/Cadastro.php" onSubmit="return ValidateRequiredFields()">


Nº do Processo: <br><input type="text" name="nr_processoCA" class="input-xlarge"><br>

<div class="row-fluid" style="text-align:center;">
    <input type="submit" class="btn btn-primary btn-large" value="Gravar">
</div>   

</form>

</body>
</html>
Collayer answered 27/9, 2012 at 14:20 Comment(0)
A
2

i suggest to put a button that will run the form if true:

 <input type='button' onclick="if (ValidateRequiredFields()) document.forms['theForm'].submit();" />

that's all....

Abbotson answered 27/9, 2012 at 14:8 Comment(4)
if there is an error inside the function then it wont return false and form will submit. since the form submits you wont see the error... best to test the function first.Abbotson
This is what <input type="submit"> is made for, without messing with intrusive js. If there is any error in the validation function, moving it around won't solve the issue.Chadwickchae
well at least you will see the error. if it still submits i suggest to search for prevetntdefault function. also it does marvelous job and as long as it's followed by click it's ok from the security view of all browsersAbbotson
the dude beneath me is right...always recheck the inouts in .php otherwise people with little tools can cause alot of troubleAbbotson
H
1

An object will always evaluate to true, even if it's a Boolean object with value false.

Put flag = true at the top of the function, then flag = false instead of creating a Boolean.

Hydrastine answered 27/9, 2012 at 14:14 Comment(0)
L
0

I was having a similar problem. It turned out there was an error in my validation (nested a few functions deep) which was causing JavaScript to quit execution of the function before reaching a return statement. At which point it would just continue with the submit.

My advise to anyone finding this page looking for an answer to "onsubmit method doesn't stop submit" is to step through your validation function with a fine tooth comb.

Lowpressure answered 22/1, 2014 at 16:44 Comment(0)
B
0

After looking around for an answer that worked for me I decided to just create a solution. The following code allows native HTML5 form validation to run before submitting or running another function (tested in Chrome). Make sure you return false after the function to prevent the form submission.

<input type="submit" value="Submit" onclick='if (document.getElementById("mainForm").checkValidity()) { submitData(); return false;}' />
Ballinger answered 7/11, 2016 at 2:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.