user3618922
user3618922

Reputation: 181

Javascript confirm return false if cancel

I have a Delete button like so:

<a class="btn btn-default" href="Communities.php?action=delete&id=' . $value['rb_communityId'] . '" onclick="javascript:confirm(\'Are you sure you want to delete this item?\');">Delete</a>

if the user clicks cancel on my confirm back, then I want nothing to happen, is there away if the user clicks cancel it will return false.

Upvotes: 0

Views: 27333

Answers (2)

scragar
scragar

Reputation: 6824

<a
  class="btn btn-default"
  href="Communities.php?action=delete&id=' . $value['rb_communityId'] . '"
  onclick="if(!confirm(\'Are you sure you want to delete this item?\')) return false;"
>
  Delete
</a>

Key line that changed is the onclick, where the confirmation has been wrapped in an if(!...) to catch the occasions where cancel is clicked, and returns false if that happens.

Upvotes: 7

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

javascript: is not needed in an onclick handler, because you are already in a JavaScript context.

return, however, is needed to pass the return value of confirm to the handler. When Cancel is clicked, false is returned, which then gets passed to the handler and this cancels the default action (of following the link).

Finally, NEVER use <a href="..."> for a delete action. GET-method requests should never change things on the server, especially not delete stuff. Use a form and a POST method.

Upvotes: 13

Related Questions