LostProgrammer
LostProgrammer

Reputation: 120

onsubmit return false does not work, form still submits?

This is the code

<html>

    <head>
        <script>
        function test() {
            return false;
        }
        </script>
    </head>

    <body>
        <form method="post" action="../test.php">
            <input type="submit" onsubmit="return test()">
        </form>
    </body>

</html>

how is the form still submitting, it makes no sense to me??

Upvotes: 2

Views: 7413

Answers (2)

Tushar
Tushar

Reputation: 87233

You need to stop form submission, when user submits it by clicking the submit button in the form.

Change onsubmit of the submit button to onclick

<input type = "submit" onsubmit= "return test()">

Should be

<input type="submit" onclick="return test()">
<!--                 ^^^^^^^^^^^^^^^^^^^^^^^ -->

If you want to use onsubmit, you can use it on form element.

<form method="post" action="../test.php" onsubmit="return test()">
<!--                                     ^^^^^^^^^^^^^^^^^^^^^^^^ -->
    <input type="submit" />
</form>

Upvotes: 8

Master Yoda
Master Yoda

Reputation: 531

<html>

<head>
    <script>
    function test(e) {
        e.preventDefault();
        return false;
    }
    </script>
</head>

<body>
    <form method="post" action="../test.php" onsubmit="return test(event);">
        <input type="submit">
    </form>
</body>

Upvotes: 0

Related Questions