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

javascript - Asking user confirmation before redirect to a clicked link - Stack Overflow

programmeradmin6浏览0评论

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.

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.

Share Improve this question edited May 27, 2014 at 8:31 nl-x 11.8k7 gold badges36 silver badges66 bronze badges asked May 27, 2014 at 8:24 erlandmuchasajerlandmuchasaj 2324 silver badges16 bronze badges 2
  • Are all links just anchors like <a href="url">link</a> ? – nl-x Commented May 27, 2014 at 8:26
  • 1 @nl-x yes they are! or at least those that im interested in to prevent from redirecting automaticlly they are. – erlandmuchasaj Commented May 27, 2014 at 8:28
Add a ment  | 

5 Answers 5

Reset to default 3

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();
    }
});

});

发布评论

评论列表(0)

  1. 暂无评论