Ender91
Ender91

Reputation: 71

"Are you sure you want to leave?" message still popping up even when there are no changes made to the form

Most of the time, the code below works to make sure it catches any changes made to the form but there are still a few instances where a person goes to a page, does not make any changes to the form and the message still pops up and I'm not sure why the message pops up even when there are no changes. Any help would be greatly appreciated.

PS - one of the devs said this, maybe it'll help " so the issue is that the form is not finished loading before it's serialize and saved. I add a delay and that fixed the issue but we can't rely on that."

function formUnloadPrompt(formSelector) {
var formA = $(formSelector).serialize(), formB, formSubmit = false;

// Detect Form Submit
$(formSelector).submit( function(){
    formSubmit = false;
});

 $(':submit').click(function() {
        formSubmit = true;
    });

// Handle Form Unload    
window.onbeforeunload = function(){
    if (formSubmit) return;
    formB = $(formSelector).serialize();
    if (formA != formB) return "Your changes have not been saved.";
  };
}

Upvotes: 0

Views: 44

Answers (1)

henry
henry

Reputation: 140

You can check if the DOM has been fully loaded with jQueries .ready() method. If you wrap your code in that it will only get executed once all elements have been loaded.

$( document ).ready(function() {
  // your code
});

An alternative solution would be to add an onchange event to the input fields and set a flag so you know if a user has entered anything.

In general every aspect of your javascript that deals with DOM elements should only be executed once ready has fired.

Upvotes: 1

Related Questions