'Submitting forms using JavaScript

I have been battling for the past two days with the evil onbeforeunload function in JavaScript. I have a function that warns the user when they are about to close a page. However before the page close I would like to submit the form using JavaScript's .submit().

This is my code:

function setPopUpWindow(submitForm){
    window.onbeforeunload = function () {
        if (submitForm == false ) {
        //alert("It worked");   --This code gets called so I know it works  
        document.getElementById("CancelScripting").submit();
        //return "Unsaved Data would be lost";
        }
        
    }
}

In my html I have two buttons, one is (supposed to) trigger the .submit() and the other will just ignore it.

<body>
 <form action=tett.html id="popUpForm" method=POST>
<script>setPopUpWindow();</script>
<input type="submit" id="submit_button" onclick="setPopUpWindow(true);">
<input class=b1 type=submit id="CancelScripting"  style="visibility:hidden"  value="CancelScripting" >
</body>

The `setPopWindow value for the second input is not defined so it would be false. For some reason the submit is not working well.

------------------------Edit to my question----------------------------------------------- I would like to submit the form even if the user leaves the page by closing the X button on their window. This is the reason why I have the hidden button... Looks like people misunderstood my question.



Solution 1:[1]

The only thing you can do is to ask the user if they really want to leave the page:

<head>
    <script type="text/javascript">
        var submitForm = false;
        window.onbeforeunload = function () {
            if(submitForm == false){
                return 'You have an unfinished form ...';
            }
        }
        function setPopUpWindow(type){
            submitForm = true;
        }
    </script>
</head>
<body>
   <form action="" method="post" name="SubmitForm" id="SubmitForm">
      <input type="submit" id="submit_button" onclick="setPopUpWindow(true);">
   </form>
</body>

Solution 2:[2]

I think that what you want to do is submit the form rather than the button by doing something like:

document.forms["formId"].submit();

where formId is the id of the form.

Also, I dont see anywhere in your code where your form is but your buttons should be inside of form tags.

For example, it should look like this:

<body>
<script>setPopUpWindow();</script>
<form id="formId" action="" method="post">
    <input type="submit" id="submit_button" onclick="setPopUpWindow(true);">
    <input class=b1 type=submit id="CancelScripting"  style="visibility:hidden" value="CancelScripting" >
</form>
</body>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brian Tompsett - 汤莱恩
Solution 2 Andreas Köberle