landi landi - 5 months ago 19
Javascript Question

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.

Answer

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