Joe
Joe

Reputation: 13

Confirming form submission on form created with javascript

I've run into a problem trying to get a confirmation on a dynamically created form submission. The form is being generated with information returned from an ajax call. This HTML page submits a form to a php script via ajax and the page responds back with a transaction number.
After the response, the code below creates a new "Void Transaction" button and form that will void the previous transaction.

It all works perfectly, but I can't find a way to do a confirmation (e.g. "Are you sure you want to void the last transaction?") before the new button is clicked.

<script> 
    $(document).ready(function() { 
        $('#looptransact').ajaxForm(function(response) { 
            document.getElementById("looptransact").reset();
            document.getElementById("areaCode").focus();

            jsonResponse = JSON.parse(response);

                var voidForm = document.createElement("form");
                    voidForm.method = "POST";
                    voidForm.action = "VoidTransaction.php";

                var voidFormData = document.createElement("input");
                    voidFormData.type = "hidden";
                    voidFormData.name = "TransactionNumber";
                    voidFormData.value = jsonResponse.TransactionNumber;

                var voidFormButton = document.createElement("input");
                    voidFormButton.type = "submit";
                    voidFormButton.value = "Void Transaction";

                voidForm.appendChild(voidFormButton);
                voidForm.appendChild(voidFormData);

                placeholder = document.getElementById("VoidButton");
                placeholder.appendChild(voidForm);

            document.getElementById("statusbox").innerHTML=jsonResponse.Response;
            document.getElementById("TransactionNumber").innerHTML="Transaction Number: " +jsonResponse.TransactionNumber;
        }); 
    }); 

I assumed I could add this to the document.createElement("form") call:

voidForm.onsubmit = "return confirm('Are you sure you want to void this transaction?')"

But that didn't work at all.

Here's the HTML elements that this populates:

<div id="statusbox"></div>
<div id="TransactionNumber"></div>
<div id="VoidButton"></div>

I hate to admit I've been on this for about 2 hours now.

Upvotes: 0

Views: 115

Answers (2)

xManh
xManh

Reputation: 67

try this:

$(voidForm).submit(function(){
    if(confirm('Do you want to subhmit?'))
        return true;
    else
        return false;
});

Upvotes: 0

David Buchbut
David Buchbut

Reputation: 158

You can change the button type from submit to button and then add this code:

voidFormButton.onclick = function () {
    if (confirm('Are you sure you want to void this transaction?')) {
        voidForm.submit();
    }
}

Upvotes: 1

Related Questions