简体   繁体   中英

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.

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.

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM