0

I'm trying to use function onload="submit()" on my form, but when the page loads, it does it multiple times. The result is there, but how can I stop the loop? How can I use it only once? Here's my code:

    <script type="text/javascript">
    function submit() {
    if (!sessionStorage.getItem("submitted")) {
        sessionStorage.setItem("submitted", "true");
        document.post.submit();
    }
}
    </script>

    <body onload="submit()">
        <form method="post" id="post" name="post">
              //stuff here
             <input id="submit" type="submit" value="Valider" name="test" class="submit">
        </form>

Is there anything i'm doing wrong? Or there's any better way to make it?

Thank you for your time and help!

C. Monkey
  • 45
  • 9

1 Answers1

2

Use sessionStorage to remember if you've already submitted the form, so you don't do it again.

function submit() {
    if (!sessionStorage.getItem("submitted")) {
        console.log("submitting");
        sessionStorage.setItem("submitted", "true");
        document.getElementById("post").submit();
    } else {
        console.log("already submitted, not repeating");
        sessionStorage.removeItem("submitted");
    }
}

Also, don't use name="submit" and id="submit" for the submit button. See "Submit is not a function" error in JavaScript

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612