Notify user before exiting the page if there is an unsaved form using TypeScript

I am working on a script that handles unsaved text inputs.

Here is the code for the script:

export class Unsave {
    public static unsave_check(): void {
        let unsaved = false;
        $(":input").change(function(){ 
            unsaved = true;
            console.log(unsaved);
        });

    function unloadPage(){ 
        if(unsaved){
            return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
        }
    }

    }
}

Later, I use it in another script like this:

`window.onbeforeunload = Unsave.unsave_check();`

However, despite seeing that function unloadPage() is never called, why is that so? I notice that the value of unsaved changes to true, but I still do not receive an alert message when trying to go back.

How can I address this issue?

Thank you for your help!

Answer №1

It is recommended to invoke the Unsave.unsave_check() function once the form has been initialized and bind the unloadPage method to the window.onbeforeunload event (consider making it static or using another approach for non-static methods by instantiating the object). To ensure both methods can access the value, consider moving the variable unsaved from the function scope to a private class field.

export class Unsave {
    private unsaved: boolean = false;

    public register() {
        $(":input").change(() => {
            this.unsaved = true;
            console.log(this.unsaved);
        });
    }

    public unloadPage() {
        if (this.unsaved) {
            return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
        }
    }
}

// Initialize after form setup
const unsaveChecker = new Unsave();
unsaveChecker.register()
window.onbeforeunload = () => unsaveChecker.unloadPage()

Answer №2

It is recommended to utilize the unloadPage function within the window.onbeforeunload event handler as shown below:

export class UnsavedDataHandler {
    private static unsaved: boolean = false;
    public static checkForUnsavedChanges(): void {
        UnsavedDataHandler.unsaved = false;
        $(":input").change(function(){ 
            UnsavedDataHandler.unsaved = true;
            console.log(UnsavedDataHandler.unsaved);
        });
    }
    public static unloadPage(): string { 
        if(UnsavedDataHandler.unsaved){
            return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
        }
    }

}

Then set

window.onbeforeunload = UnsavedDataHandler.unloadPage();
and remember to call checkForUnsavedChanges somewhere else in your code...
For example:

document.addEventListener("DOMContentLoaded", function() {
    UnsavedDataHandler.checkForUnsavedChanges();
});

Note: The naming convention for unloadPage and checkForUnsavedChanges may not be consistent - one is in camel case, the other in snake case.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

One-page application featuring preloaded data from a backend API

Imagine building a single-page application that relies heavily on client-side interactions communicating with the server through API methods. When we land on the index page that displays all records from the database, we essentially make two initial requ ...

Exploring a POST request using jQuery

Apologies if I struggle with my question or use incorrect terminology, as I am new to this. I have a basic web service that processes a JSON string and returns a JSON result. Here is the code: $jsonStr = ''; if(isset($_POST['request'] ...

`Generating an ever-changing masonry layout on a website using live data`

I'm currently working on a new web project and I want to incorporate a masonry view for the images on the homepage. The plan is to host this project on Azure, using blob storage for all the images. My idea is to organize the images for the masonry vi ...

Using React: Implementing conditional checks within the render() method of functional Components

When working with my usual React class Components, I typically perform some checks within the render() method before returning conditional html rendering. However, when using a react functional component, I noticed that there is no render() method availabl ...

How to use jQuery to gather all the text from a textarea

Is there a way to automatically select all text inside a textarea when it is clicked on? Additionally, can this selection be deselected by clicking again? ...

Acquiring data within a jade template in order to generate static HTML pages

I am struggling to pass data to a jade template in order to generate static content. While I am not well-versed in node.js and express, I use jade as a template engine for creating static html. Many of the requests in the jade issue list pertain to includ ...

Developing numerous global objects within the context of JavaScript in Rails

I have an instance object called @cameras in my cameras controller's map method and am extracting necessary values from it for my specific purpose: + @cameras = load_user_cameras(true, false) + @map_data = [] + @cameras.each do |camera| + ...

How to mimic the "show more" feature on Twitter without using ajax?

I have a list of 50 items that I want to display 10 at a time with a "More" link at the bottom. Can someone guide me on how to achieve this effect without using ajax? You can refer to this example for reference. Your help is much appreciated! UPDATE: Tha ...

Using jQuery to access a server-side SQL database through PHP

After searching for an example on connecting a client to a server's SQL database using JQuery, AJAX, and PHP, I came across this seemingly well-executed guide: Example Link. All my PHP files and the jQuery library (javascript-1.10.2.min.js) are contai ...

Leverage the OpenWeather Icons to Pinpoint Locations on a Leaflet Map

Having some trouble incorporating weather icons from an openweather API call as markers on my leaflet map. The icons should appear in a popup on the marker within an img tag. However, despite confirming the correct icon URL through console.log, they only ...

Is there a restriction on the number of routes available from Google Maps Directions Service?

Utilizing the Google Maps Directions API, I am able to calculate the distance between the current user's location and various stores. Everything functions properly until I exceed 10 store locations, at which point the API ceases to operate due to its ...

Tips for showing the database list based on the chosen value in the drop-down menu

manage_bank Hey there, I need some assistance with displaying the bank name based on the selected dropdown option. For instance, if we choose 50 records, it should display 50 records of the bank name from the database. Additionally, I want the selected v ...

Looking to retrieve object values in JavaScript in a dynamic manner?

Imagine having an array of objects with nested objects. The data is always changing, meaning the keys may vary each time. For instance: [ { "uuid": "53e7202c-28c8-4083-b910-a92c946a7626", "extraIdentifiers": { "National ID": "NAT2804" }, ...

Troubleshooting Challenges in JavaScript/jQuery Hangman Game

Having trouble with my hangman game's game loop. Attempting to replace correct letters as the game runs through the word, but it's currently: looping through the word checking if the guessed letter is in the word returns index[0] Tried splitti ...

Guide to integrating custom fields in Wordpress with mapbox-gl js to generate map markers

Currently, I am in the process of generating a map that will display various points using Mapbox and WordPress. To achieve this, I have set up a custom post type within WordPress where the coordinates are stored in custom meta fields. Although the fields h ...

AngularJS UI-Router: Utilizing Optional Parameters

.state('registration', { url:'/app/registration/:ref', templateUrl: 'partials/registration.html', }) This is my configuration for routing using ui-route. It functions properly when I go to localhost:80/r ...

The One-Click File Upload Dilemma

I have replaced the regular upload input + submit button with an icon. My goal is to automatically start the upload process when a file is chosen by the user. However, currently nothing happens after the file selection. <form action="upload.php" method ...

Arrange arrays with multiple dimensions in JavaScript based on their ranges

Seeking assistance on sorting a multi-dimensional array returned from an API to enable users to choose a range based on beats. I'm currently facing challenges with the data my API is returning. var myObj = [{ title: 'title one', be ...

Navigating Users to View Their Recently Posted Topic After Clicking Submit in CodeIgniter

Users are able to write articles using a form on my website. Once they submit the form, I want the system to redirect them to view their new post (typically displaying a success message). Controller if ($this->form_validation->run() == TRUE) { ...

Error encountered: No matching overload found for MUI styled TypeScript

I am encountering an issue: No overload matches this call. Looking for a solution to fix this problem. I am attempting to design a customized button. While I have successfully created the button, I am facing the aforementioned error. Below is my code ...