Home >Web Front-end >JS Tutorial >How to Prompt Users to Confirm Unsaved Changes Before Leaving a Page?
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!