Onsubmit Method Doesn't Stop Submit
Solution 1:
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;
}
Solution 2:
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>
Solution 3:
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....
Solution 4:
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.
Solution 5:
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.
Post a Comment for "Onsubmit Method Doesn't Stop Submit"