About why the Onsubmit method returns a false form and is still submitted

Today, when I was working on a project, I came across a strange phenomenon. The following HTML code looks normal and has no problems (except that the pages used for the example are not arranged, so it's ugly):

<html>
<head>
<script type="text/javascript">
    function initadd() {
        var name = document.getElementById("name");
        if (name.value.length < 2) {
            alert("Please enter the correct user name");
            return false;
        }
        return true;
    }
</script>
</head>

<body>
    <form action="test.jsp" onsubmit="initadd()">
        //Add users:<input type="text" name="name"> 
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Running Page:

I didn't type anything. Click the Submit button and a prompt pops up. Everything looks normal:

But then a miracle happened and the page was submitted:

After a long tangle, we finally found the reason: onsubmit is a method that is generated when the form is submitted, that is, it submits the form first and then invokes the method, which is a bit like do while.

If you see a similar conclusion on the web, just change the button to button type and use onclick():
Use code instead:

<html>
<head>
<script type="text/javascript">
    function initadd() {
        var name = document.getElementById("name");

        if (name.value.length < 2) {
            alert("Please enter the correct user name");
            return;
        }
        var userForm = document.getElementById("userForm");
        userForm.action = "test.jsp";
        userForm.submit();
    }
</script>
</head>

<body>
    <form name="userForm">
        //Add users:<input type="text" name="name"> <input type="button"
            value="Submit" onclick="initadd()">
    </form>
</body>
</html>

That's really OK.

However, once our form item is larger than one, onsubmit validation fails and will not be submitted:

<html>
<head>
<script type="text/javascript">
    function initadd() {
        var name = document.getElementById("name");
        var sex = document.getElementById("sex");


        if (name.value.length < 2) {
            alert("Please enter the correct user name");
            return false;
        }
        if (sex.value.length == 0) {
            alert("Please enter the correct gender");
            return false;
        }
        return true;
    }
</script>
</head>

<body>
    <form action="test.jsp" onsubmit="return initadd()">
        //Add users:<input type="text" name="name"> 
        //User gender:<input type="password" name="sex"> 
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Without entering content at this time, the form will not be submitted.

Above, record learning.

Tags: Javascript JSP

Posted on Sat, 09 May 2020 12:50:58 -0400 by willwill100