EliotPeeters
EliotPeeters

Reputation: 1

how to intercept a click on a <button> tag and stop the submit?

I have a form with some button tags, one of which is a delete button. I want to intercept the click and ask confirmation. I can intercept it with the code below, but it processes anyway no matter what I answer.

HTML:

<button type=submit id=mydelbuttonid value=delete name=deletebutton>Delete</button>

jQuery:

$('button#mydelbuttonid').on("click", function(e) {
  if (confirm('Are you sure you want to delete this record?')) {
    alert('deleting');
  }
  else {
    alert('not deleting');
    event.preventDefault();
    return false;
  }
});

I get the correct alert, but the record is deleted anyway.

Anyone have any idea how to fix this? I've searched the internet for quite a while and find a lot of solutions for <a> tags, but none for <button> tags.

Upvotes: 0

Views: 944

Answers (1)

sfletche
sfletche

Reputation: 49714

As @A.Wolff correctly points out, e !== event...

Changing event to e or vice-versa will allow preventDefault to actually get triggered (after which the return false becomes redundant).

$('button#mydelbuttonid').on("click", function(e) {
  if (confirm('Are you sure you want to delete this record?')) {
    alert('deleting');
  }
  else {
    alert('not deleting');
    e.preventDefault();
    /*return false;*/
  }
})

Upvotes: 3

Related Questions