最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript confirm return false if cancel - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question asked May 20, 2014 at 14:13 user3618922user3618922 1811 gold badge5 silver badges14 bronze badges 1
  • That is the default behavior of confirm. – Teepeemm Commented May 20, 2014 at 14:16
Add a comment  | 

2 Answers 2

Reset to default 13

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.

发布评论

评论列表(0)

  1. 暂无评论