简体   繁体   中英

Asking user confirmation before redirect to a clicked link

I have a long kind wizard form, like a survey in my site. I want to write a jQuery Function so that when the user click accidentally any link on the page ( except preview and next buttons of the wizard ), it is asked first: are you sure you want to proceed? then it is redirected to the link he clicked, if he click cancel, nothing happens..

So far What i have done is to each link of the page except (next & previw) i have added a class link_ridirect so i can grab all the anchor links. and stop redirecting.

jQuery function is as follow!

<script type="text/javascript">
<!-- HERE IS THE SEARCH FILTER -->
 //<![CDATA[
    var GLOBAL_NAMESPACE = {};
    $(document).ready(function(){
      GLOBAL_NAMESPACE.value_changed = true;
    });

    $(document).ready(function () {
      $('.link_redirect').bind('click',function (e) {
          e.preventDefault();
          if (GLOBAL_NAMESPACE.value_changed){
              var res = confirm('you have unsaved changes. Do you want to continue?');
              if(res){
                  window.location.href = $(this).attr('href');
              }else{
                  console.log('stay on same page...');
              }
          }
      });
    });
//]]>
</script>

So what i want to do is how can i declare a Global variable to keep track of all field state. So if a field changes, to make it true and call the prevent function.

How about doing this:

 $('a').click(function(){return confirm("are you sure?");});

Place it at the bottom of your html, or in the onload of your page, or in the document ready as you suggested in your OP.

edit If you only want to do this if your variable changesDetected is true , then do it like this:

 $('a').click(function(){return !changesDetected || confirm("are you sure?");});

It looks like you have code to interrupt default A-tag clicks already, so the crux of this is to detect when a field has changed such that you want to ask if they want to save before navigating away ?

Here's a JSFiddle Detect Field Changes :

It adds an onchange event to all editable fields whcih sets the global stae to true if something changed.

If the user enters a field then exits without changing, no change is detected.

function setup() {
  // bind the change event to all editable fields. Runs on load(or doc ready)
  $("input,select").bind("change",function(e) {
      GLOBAL_NAMESPACE.value_changed = true;
  });  
};

you need to use beforeunload event. This event handled when you go out from page.

$(this).on("beforeunload", function () {
                return 'are you sure';
            });

if you need, that event called not for preview button and next, you can unbind this event handler.

    $('#myPreviewButtonId').click(function()
{
          console.log('preview clicked');
          $(this).unbind("beforeunload");
});

 (function($) { $.fn.checkFileType = function(options) { var defaults = { allowedExtensions: [], success: function() {}, error: function() {} }; options = $.extend(defaults, options); return this.each(function() { $(this).on('change', function() { var value = $(this).val(), file = value.toLowerCase(), extension = file.substring(file.lastIndexOf('.') + 1); if ($.inArray(extension, options.allowedExtensions) == -1) { options.error(); $(this).focus(); } else { options.success(); } }); }); }; })(jQuery); $(function() { $('#image').checkFileType({ allowedExtensions: ['jpg', 'jpeg'], success: function() { alert('Success'); }, error: function() { alert('Error'); } }); }); 
 label { display: block; font-weight: bold; margin-bottom: 0.5em; } 
 <form action="#" method="post" enctype="multipart/form-data"> <div> <label for="image">Upload image (JPEG only)</label> <input type="file" name="image" id="image" /> </div> </form> 

You must prevent the default action on a if result of confirm function is false

$(document).ready(function () {
$(".deleteJob").on("click", function (e) {
    if (!confirm("Are you Sure want to delete!")) {
        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