Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my HTML form still submit when I return false from onsubmit?

I wrote a simple script for validating login form as follows:

<script type="text/javascript">
    function validateLoginForm(){
    var idV = document.forms["LoginForm"]["id"].value;
    var pwdV = document.forms["LoginForm"]["pwd"].value;

    if (idV == null || idV == "" || idV.length < 5) {
          alert("user ID must be filled and of more than 4 characters!!");
          id.focus();
          return false;
    }

    if (pwdV == null || pwdV == "" || pwdV.length < 5) {
        alert("Password must be filled and of more than 4 characters!!");
        pwd.focus();
        return false;
    }

    return true;
}
</script>

and call it as :

<form name="LoginForm" method="POST" onsubmit="return validateLoginForm()" action="Login" >
.
.
.
.
</form>

The problem is that javaScript gives out the alert as i set correctly but in the end the Login servlet also called automatically, which is a wrong thing..Why this happens? Any solution?

like image 355
Asif Avatar asked Oct 11 '11 08:10

Asif


People also ask

What happens when Onsubmit returns false?

return false cancels the default submit action(stops the submission of form). It means Do nothing . Return the control flow.. It means that do nothing on submit.

How do I stop HTML form from submitting?

The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.

How does Onsubmit work in HTML?

The onsubmit attribute provides the script datas to executed whenever the submit event is occurred so it does not submit the datas to the server with the help of submit() function it will be postponed to the server side.

How Stop JavaScript submit?

One way to stop form submission is to return false from your JavaScript function.


2 Answers

Redirect to Login happens because you have js error.

You dont define variable id and psw.

So when you try id.focus() or psw.focus() - you have js error and return true by default

So add this code:

var id = document.forms["LoginForm"]["id"];
var pwd = document.forms["LoginForm"]["pwd"];
var idV = document.forms["LoginForm"]["id"].value;
var pwdV = document.forms["LoginForm"]["pwd"].value;
like image 93
Vasily Avatar answered Sep 27 '22 23:09

Vasily


Well, strangely enough my form was still submitted even when I returned false from my function and returned that function's return to the form's onsubmit... I even tried:

onsubmit="return false;"

Not sure what was going on... in any case moving the event trigger to the submit button's onclick event fixed the problem.

Update: Ended up finding that the code I was editing had another JS handler attached to the onsubmit event which is why it was ignoring my return false;

like image 35
Serj Sagan Avatar answered Sep 28 '22 01:09

Serj Sagan