Javascript onclick confirm form submit and flask app

Javascript onclick confirm form submit and flask app

Problem Description:

I want to add a confirmation to a form action:

        <form action="/delete" method="post">
            <button id="deleteForm" class="btn btn-danger" onclick="deleteConfirm(this.form)">Delete</button>
        </form>

And in my script.js I wrote the function:

function deleteConfirm() {
    
    let text = "Are you sure?nOk=Delete all data.";
    if (confirm(text) == true) {
        document.getElementById("deleteForm").submit();
    } else {
        alert("Cancelled.");
    }
}

But with these codes when I click either ok or cancell, the form will submit. when I click cancel the alert show up but then the action /delete will execute.

Is this an attribute of flask?
Are there another ways to do this?

Solution – 1

You need to add attribute type="button" to your button, and id "deleteForm" add to form

<form id="deleteForm" action="/delete" method="post">
  <button type="button" class="btn btn-danger" onclick="deleteConfirm(this.form)">Delete</button>
</form>

Solution – 2

No need to use the onclick event of the button. Instead, attach type="submit" with your buttion. And add the onsubmit attribute with your form. This is the standard way of doing what you mentioned.

function deleteConfirm(myForm) {
    let text = "Are you sure?nOk=Delete all data.";
    if (confirm(text) == true) {
        return true;
    } else {
        alert("Cancelled.");
        return false;
    }
}
<form action="/delete" method="post" onsubmit="return deleteConfirm(this);">
    <button id="deleteForm" type="submit" class="btn btn-danger">Delete</button>
</form>

Solution – 3

There are like many ways to approach this question, but what i would do is that instead of having an entire javascript function just to display a on click alert i would just wrap it around a input.

<input type="submit" value="Delete"
                   onclick="return confirm('Are you sure you want to delete this data?')">

I have used this for like flask data delete and when the user clicks cancel it does not submit the form.

Here is an example of what i just used:
https://jsfiddle.net/12f6bvkq/

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject