Javascript confirm dialog

后端 未结 5 858
野性不改
野性不改 2021-02-05 15:59

I want to add a confirm dialog to a delete button to ask the user whether it is ok or not deleting the selected item.

If not, nothing should happend, else a url should be

相关标签:
5条回答
  • 2021-02-05 16:33

    There is a jQuery plugin that does just that: jquery.confirm.

    Example:

    <a href="home" class="confirm">Go to home</a>
    

    JS code:

    $('.confirm').confirm();
    

    If the user confirms, he is redirected to the link of the <a>, else nothing happens.

    0 讨论(0)
  • 2021-02-05 16:39

    Better (though far from ideal!): turn it around. Don't let the link do anything, unless you got JavaScript:

    <a href="#" 
      onclick="if confirm('Sure?') { window.location='http://mysite.de/xy/delete';}">
        Click to delete
    </a>
    

    This at least prevents the link to work without JavaScript. This also reduces the risk of the link accidentally being crawled by Google, or even by some local plugin. (Image if you had a plugin that would try to load/show as thumbnail) the target page on hover of a link!)

    Still, this solution is not ideal. You will actually browse to the url, and the url might show up in the history because of that. You could actually delete Bob, create a new Bob, and then delete that one by accident by just clicking 'back' in the browser!

    A better option would be to use JavaScript or a form to post the desired action. You can make a request to the server with the POST method, or arguably better, the DELETE method. That should also prevent the urls from being indexed.

    0 讨论(0)
  • 2021-02-05 16:44

    You can use this: Download a bootboxjs from:[1]: http://bootboxjs.com/

    Create the Button (HTML)

    <button type="submit" id="btn">Delete</button>
    

    Call the Dialog:

      var myBtn = document.getElementById('btn');
    
    
      myBtn.addEventListener('click', function(event) {
          bootbox.confirm({
              size: "small",
              message: "Are you sure?",
              callback: function (result) {
                  /* result is a boolean; true = OK, false = Cancel*/
                  if (result == true) {
                      alert("ok pressed");
                  }
                  else {
                      alert("cancel pressed");
                  }
              }
          })
      });
    
    0 讨论(0)
  • 2021-02-05 16:50

    You can return the confirm() (which returns true/false), like this:

    <a href="mysite.de/xy/delete" onClick="return confirm('You sure??');">Delete</a>
    

    You can test it here

    0 讨论(0)
  • 2021-02-05 16:51

    Consider what happens if the user has javascript disabled, or if google comes along and spiders the link. Will your entity be deleted?

    A better way would be to post a form to delete.

    0 讨论(0)
提交回复
热议问题