santa
santa

Reputation: 12512

Save form input with jQuery

I have a form with multiple fields on a page. If a user fills in the fields and then decides to leave the page he/she will loose it. I'd like to add an alert using jQuery UI dialog to alert them about the data that has not been saved. I think I can get the buttons and dialog figured out. My question is: how do I detect them leaving the page without submitting the form?

Upvotes: 0

Views: 558

Answers (3)

Fenton
Fenton

Reputation: 250892

Here is a quick example - you need to be able to detect whether the form has been submitted as part of an onbeforeunload event.

var formSubmitted = false;
window.onbeforeunload = function () {
    if (!formSubmitted) {
        return confirm("Are you sure you want to leave the page without submitting the form"?);
    }
};

document.getElementById("myForm").onsubmit = function () {
    formSubmitted = true;
};

Upvotes: 3

Alex KeySmith
Alex KeySmith

Reputation: 17091

I'd recommend taking a look at the onbeforeunload event, here is some Mozilla developer connection documention to get you started: window.onbeforeunload

Upvotes: 0

casablanca
casablanca

Reputation: 70701

Have a look at the onbeforeunload event. However, keep in mind that some newer browsers like Firefox 4 do not allow you to customize the message that is displayed.

Upvotes: 0

Related Questions