0

EDIT: My question is different from the 'supposedly duplicate' because mine is checking how to not trigger off an event when a link is clicked, the other question is about how to detect changes in a form.

I am using a function (taken from here) to detect any changes made to a form before leaving the page, this works fine however it also triggers off when I click the save button as I am using the onbeforeunload event to fire of the function and I want to prevent this from happening when I click my save button.

Here is my event:

window.onbeforeunload = function (e) {
    e = e || window.event;
    if (formIsDirty(document.forms[0])) {
        // For IE and Firefox
        if (e) {
            e.returnValue = "You have unsaved changes.";
            alert("You have unsaved changes.");
        }
        // For Safari
        return "You have unsaved changes.";
        alert("You have unsaved changes.");
    }
};

How can I prevent this event from firing when this particular save link is clicked?

Link:

<a id="ctl00_ContentPlaceHolder1_lbtnSave" href='/save'>
<img id="ctl00_ContentPlaceHolder1_Image5" class="imgvalign" src="../../images/icons/save.gif"> Save
 </a>
Community
  • 1
  • 1
user3574492
  • 6,225
  • 9
  • 52
  • 105
  • Possible duplicate of [Detecting Unsaved Changes](http://stackoverflow.com/questions/155739/detecting-unsaved-changes) – Evan Davis Jan 08 '16 at 16:35
  • The answer to your question is actually in your linked question. You need to track that state of the form and use a click handler on the save button to update that state. – Evan Davis Jan 08 '16 at 16:35
  • No it is not, Please show me the answer then? – user3574492 Jan 12 '16 at 21:47

1 Answers1

0
event.target //DOM object.

event.target.id  //id of source element.

sourceElement = $(event.target.id); // will get you jQuery object

you can check the element is Submit button or not.If yes then no need to display the message

Anoop LL
  • 1,548
  • 2
  • 21
  • 32
  • he can check the id of element no need of Jquery – Anoop LL Jan 07 '16 at 15:31
  • `event.target.id` doesn't do anything in my case, here is what I have used: `if (e.target.id === "ctl00_ContentPlaceHolder1_lbtnSave") { //save button was clicked return false; }` – user3574492 Jan 08 '16 at 11:12
  • @user3574492 why you need to fire an event. You can use the function to detect changes in the save click function na. Correct me if am wrong – Anoop LL Jan 08 '16 at 14:20
  • @AnoopLL I am using the `window.onbeforeunload` event to detect if the user tries to navigate away from the current page. This is why I am using an event to try to get the target id, the target id is the save button – user3574492 Jan 08 '16 at 14:35