简体   繁体   中英

SweetAlert while navigating to other page

In my application if I didnot click save and want to navigate from current page it should ask sweet alert are you sure want to leave? and two buttons save and leave . How can I do that.

Currently I am using jquery and It shows sweetalert box when I click on any anchor tag but immediately navigates to other page.

My Code is

jQuery(document).click(function(e) {
                if (jQuery(e.target).is('a')) {
                    swal({
                        title: "Are you sure?",
                        text: "Want to continue without saving?",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#DD6B55",
                        confirmButtonText: "Leave",
                        closeOnConfirm: false,
                        html: false
                        }

                    );
                }    
        }); 

At first you need to prevent default behavior of an <a> element since you missed it, it will still redirect regarding of your action, second is that you need to redirect user if confirm was clicked in swal like:

jQuery(document).click(function(e)
{
  if (jQuery(e.target).is('a'))
  {
    // Prevent default behavior
    e.preventDefault();

    swal({
      title: "Are you sure?",
      text: "Want to continue without saving?",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "Leave",
      closeOnConfirm: false,
      html: false
    }, function (isConfirm) {

      if (isConfirm)
      {
        // If user clicked confirm navigate away
        window.location = jQuery(e.target).attr("href");
      }
    });

    return false;
  }
});

hope that helps

Take a look at Event.preventDefault() or e.preventDefault()

That anchor tag a will create an event to navigate to its url, even if it's href=# .

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