Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  149] [ 5]  / answers: 1 / hits: 25282  / 12 Years ago, thu, september 27, 2012, 12:00:00

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 processon';
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>

More From » html

 Answers
69

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 processon';
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


[#82876] Wednesday, September 26, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
longd

Total Points: 616
Total Questions: 110
Total Answers: 101

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;