Navigate away from tab warn about unsaved changes

Navigate away from tab warn about unsaved changes

Hi guys,

I have a page with multiple tabs using the tabs from the JQueryUI.

On each tab i have a form with multiple elements and a save button.

What i need is to fire a warning whenever the user clicks on a different tab and the contents of the tab where the user was have changed.

The structure is something like this:

  1. <div id="tabs">
      <ul>
        <li id="t1"><a id="aTabMain" href="#tabs-1">Main</a></li>
        <li id="t2"><a id="aTabAreas" href="#tabs-2">Areas</a></li>
        <li id="t3"><a id="aTabImages" href="#tabs-3">Images</a></li>
      </ul>
     
      <div id="tabs-1">
        <form id="form1">     
       
        </form>
      </div>
     
      <div id="tabs-2">
        <form id="form2">   
       
        </form>
      </div>
     
      <div id="tabs-3">
        <form id="form3">   
       
        </form>
      </div>
     
    </div>
With some inputs and a save button inside every form.

What i want to achieve is that whenever the user is editing the input values inside a tab/form, and attempts to navigate to a different tab, a check needs to be performed to validate if the tab the user was editing has anything different from when he first opened it, and if so, fire a warning to the user.

I do not want to make a personalized code version, where i would need to write a specific block of code for each of the anchors, but rather a generalized one that can account for N tabs and forms.

I was able to create a selector taht only fires when a tab different from the curent one is clicked:

  1. $("#tabs > ul > li > a:not(#" + $("#tabs > ul > li.ui-state-active > a").attr('id')).click(function () {
  2.        var currentTab = $("#tabs > ul > li.ui-state-active > a");
           alert(currentTab.attr('id').substring(4));
  3. });

but even though it fires on the correct events, the alert always returns the newly opened tab instead of the previously oppened one, so i'm unable to reserialize the form and compare its value with a previously saved one to access if any changes were made, since i cannot access what the previously oppened tab was, and consequently its respective form.

Any idea how i can accomplish this?