Lewis Clarke
Lewis Clarke

Reputation: 69

Cancel a form submission with JS

for arguments sake let's say this is my code.

function the_delete() { 

if(confirm('Delete your Account')){
alert("Account Deleted, Redirecting to homepage");
} else {
//Stop the submit
}

}
<form method="post" action="my-account/settings/delete-account">
 <button class="btn" onclick="the_delete()">Delete Account</button>
     </form>

How do I stop the form submitting when user presses cancel?

thanks

Upvotes: 0

Views: 34

Answers (1)

Quentin
Quentin

Reputation: 943163

You need to return a true or false value from the onclick function.

This means you need to modify both the onclick function and the the_delete function.

function the_delete() {

  if (confirm('Delete your Account')) {
    alert("Account Deleted, Redirecting to homepage");
    return true;
  } else {
    return false;
  }

}
<form method="post" action="my-account/settings/delete-account">
  <button class="btn" onclick="return the_delete()">Delete Account</button>
</form>

Modern JavaScript (targetting browsers more modern than Internet Explorer 8) would bind event handlers with JavaScript and manipulate the event object instead.

function the_delete(event) {
  if (confirm('Delete your Account')) {
    alert("Account Deleted, Redirecting to homepage");
  } else {
    event.preventDefault()
  }
}

document.querySelector("form").addEventListener("submit", the_delete);
<form method="post" action="my-account/settings/delete-account">
  <button class="btn">Delete Account</button>
</form>

Upvotes: 2

Related Questions