简体   繁体   中英

Confirm dialog posting on Cancel button?

I'm using the following <a> tag to display a simple confirm which it does. However, when I click the Cancel button it still performs the post method. From my understanding, having the return in front of confirm should cause the form to not post if the Cancel button is clicked.

<a href="#" 
   data-potr-action="delete"
   data-potr-val="@item.RID"
   onclick="return confirm('Are you sure you want to delete this Request?');"
   class="btn btn-default btn-sm">
    <i class="glyphicon glyphicon-trash"></i> Delete
</a>

I have this code at the end of the page but I don't think it has anything to do with the issue. I didn't thinking it would fire the click event when selecting Cancel in the Confirm dialog.

This just takes the values in the data-action and data-value and stores them to a hidden field. This is done on click which it shouldn't be getting to.

@section scripts {
    <script>
    $(document).ready(function () {
      // Hook events on buttons and anchors
      buildClickEvents();
    });

    // Hook events on buttons and anchors
    function buildClickEvents() {
      $("[data-potr-action]").on("click", function (e) {
        e.preventDefault();

        $("#EventCommand").val(
            $(this).data("potr-action"));

        $("#EventArgument").val(
            $(this).attr("data-potr-val"));

        $("form").submit();
      });
    }
    </script>
}

To answer your question no confirm doesn't block form post. It return true if pressed "OK" or false if pressed "Cancel" button. See this from W3c

What you could is as below:

function buildClickEvents() {
  $("[data-potr-action]").on("click", function (e) {
    e.preventDefault();
    var result = confirm('Are you sure you want to delete this Request?');
    if(result == false){
       return;
    }
    $("#EventCommand").val(
        $(this).data("potr-action"));

    $("#EventArgument").val(
        $(this).attr("data-potr-val"));

    $("form").submit();
  });
}

And remove the below from a tag:

onclick="return confirm('Are you sure you want to delete this Request?');"
  $("[data-potr-action]").on("click", function (e) {
    if(confirm("your message")){
        $("#EventCommand").val(
            $(this).data("potr-action"));

        $("#EventArgument").val(
            $(this).attr("data-potr-val"));

        $("form").submit();
    }

    e.preventDefault();


  });

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