Home > Software engineering >  Javascript onclick confirm form submit and flask app
Javascript onclick confirm form submit and flask app

Time:12-05

I want to add a confirmation to a form action:

        <form action="/delete" method="post">
            <button id="deleteForm"  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?

CodePudding user response:

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"  onclick="deleteConfirm(this.form)">Delete</button>
</form>

CodePudding user response:

prevent the form from being submitted when the user clicks "Cancel", you can add a return false; statement at the end of the deleteConfirm() function

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

prevent the form from being submitted when the user clicks "Cancel", but it will still be submitted when they click "OK".

EDIT :

Wrap inside this one if still not working :

function deleteConfirm() {

let text = "Are you sure?\nOk=Delete all data.";
if (confirm(text) == true) {
    return true;
} else {
    alert("Cancelled.");
    return false;
}
}

CodePudding user response:

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" >Delete</button>
</form>

CodePudding user response:

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/

  • Related