Home >Web Front-end >JS Tutorial >How to Prompt Users to Confirm Unsaved Changes Before Leaving a Page?

How to Prompt Users to Confirm Unsaved Changes Before Leaving a Page?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-03 13:59:10199browse

How to Prompt Users to Confirm Unsaved Changes Before Leaving a Page?

Confirming Unsaved Changes

Question: How do you display a confirmation message when a user navigates away from a page with unsaved changes?

Tracking Changes:

To track changes, you can use event listeners that listen for changes in input fields or other elements that store data. When a change occurs, set a flag to indicate that there are unsaved changes.

Displaying Confirmation:

To display a confirmation message, you can use the window.onbeforeunload event. It triggers when the user attempts to navigate away from the page. In this event handler, check if there are any unsaved changes. If there are, display a confirmation message using confirm().

Example:

// Create a flag to track changes
var hasUnsavedChanges = false;

// Add an event listener to input fields
$('input').on('change', function() {
  hasUnsavedChanges = true;
});

// Create an event handler for window.onbeforeunload
window.onbeforeunload = function() {
  if (hasUnsavedChanges) {
    return "Are you sure you want to leave this page? You have unsaved changes.";
  }
};

The above is the detailed content of How to Prompt Users to Confirm Unsaved Changes Before Leaving a Page?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn