landi landi - 1 year ago 106
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

so i can grab all the anchor links. and stop redirecting.

jQuery function is as follow!

<script type="text/javascript">
GLOBAL_NAMESPACE.value_changed = true;

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

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 Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download