Warning users before navigating away from a page with an incomplete form (Code restructuring)

Creating a code that alerts the user when they have any "unsaved" form in the View

Check out this script:

  import { __ } from "./translation";
export class Unsave {
    private unsaved: boolean = false;
    public register(): void {
        $(":button, :submit").on("click", () : void => {
            window.onbeforeunload = (): void => null;
        });
        $(":input" || ":checked").change(() => {
            this.unsaved = true;
        });
    }
    public unloadPage() : string {
        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?");
        }
    }

}

And here's how it's called in the main script:

 const unsaveChecker = new Unsave();
unsaveChecker.register();
window.onbeforeunload = () => unsaveChecker.unloadPage();

Is there a way to refactor it so we can just write Unsave.*** in the main script?

Answer №1

I have successfully restructured this piece of code

Below is the modified code snippet:

export class Unsave {
private static unsaved: boolean = false;
public static unsave_check(): void {
    $(":button, :submit").on("click", () : void => {
        window.onbeforeunload = (): void => null;
    });
    Unsave.unsaved = false;
    $(":input" || ":checked").change(() => {
        Unsave.unsaved = true;
    });
    window.onbeforeunload = (): string => this.unloadPage();
}
public static unloadPage() : string {
    if (Unsave.unsaved) {
        return __("Du har olagrade ändringar på den här sidan. Vill du lämna den här sidan och kasta bort dina ändringar eller stanna kvar på den här sidan?");
    }
}

}

Don't forget to include the following line in the main script:

    Unsave.unsave_check();

UPDATE

For further improvement, you can utilize the bind/unbind function:

export class Unsave {
private static unsaved: boolean = false;
public static unsave_check(): void {
    $(":button, :submit").on("click", () : void => {
        $(window).unbind("beforeunload");
    });
    Unsave.unsaved = false;
    $(":input" || ":checked").change(() => {
        Unsave.unsaved = true;
    });
    $(window).bind("beforeunload", (): string => {
        return this.unloadPage();
    });
}
public static unloadPage() : string {
    if (Unsave.unsaved) {
        return __("Du har olagrade ändringar på den här sidan. Vill du lämna den här sidan och kasta bort dina ändringar eller stanna kvar på den här sidan?");
    }
}

}

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

After reaching a total of 20 entries, req.body will automatically convert the array into an

I have the ability to dynamically add properties to my form: <form action=""> <div class="property"> <label>Name : <input type="text" name="properties[1][name]"></label> <label>Order : <input type="text" na ...

When reopening the modal in Bootstrap V5 with jQuery, the close event may not trigger as expected

When trying to implement special functionality in my modal close event using sweetalert2, I encountered an issue where the close event does not trigger again after closing the modal for the first time. Check out a live example here: https://codepen.io/th ...

Different XML sources can be used for every request with jQuery Ajax

Is there a way to alternate between two XML data sources on each page load? Currently, I am using an ajax request to retrieve data from one source: $(document).ready(function() { $.ajax({ type: "GET", url: "sou ...

What is the best way to navigate to a different page, such as Google, using Node.js?

I need to retrieve a number to store in a short variable, and then search the database for a corresponding shortUrl associated with that number. If a match is found, I want the response to be the full URL, such as www.google.com. For example, if a user ty ...

Tips for accessing a file in AngularJS

Can AngularJS be used to read files? I am interested in placing the file within an HTML5 canvas for cropping purposes. I was considering implementing a directive. Below is the JavaScript code that I plan to include in my directive: function readURL(input ...

What is the reason for the DOMException constructor deriving directly from Function.prototype, while the DOMException prototype derives directly from Error.prototype?

Why is DOMException different from AggregateError, EvalError, and others in terms of its prototype chain? Both of these statements are true: Object.getPrototypeOf(DOMException) === Function.prototype Object.getPrototypeOf(DOMException.prototype) === Error ...

Connecting a specific URL of an API to a single mobile app: A step-by-step guide

Currently, my API includes a user registration system that is utilized by a mobile application. Most of the URLs are restricted for anonymous users and require a token key for authorization, except for the register URL. The register URL needs to remain op ...

Issue with Material UI v5: Uncaught TypeError - Unable to access properties of an undefined object (specifically 'create')

After setting up the ThemeSetting.tsx context, I encountered an issue where I could not utilize <Button><Button> and other components that rely on the theme from Material UI React.js in TypeScript: error TypeError: Cannot read properties of u ...

"Unraveling the Mystery of jQuery In

I am facing an issue with integrating jQuery into my code. I have always followed the same method, which has worked in the past, but now it seems to be causing problems for me. I suspect it may be because I am not on my usual laptop, although when I visite ...

How can hover effects be incorporated within an inline style?

I utilized the Button component from ant design and adjusted its color using style. Now, I am looking to add a hover color effect to this Button. How can I achieve this? export default class NavBar extends React.Component{ render(){ return( ...

NodeJS produces identical outcomes for distinct requests

RESOLVED THANKS TO @Patrick Evans I am currently working on a personal web project and could use some assistance. In my website, users are prompted to upload a photo of their face. When the user clicks the "upload" button, the photo is sent with a request ...

When pasting content that exceeds a certain height, Quill will automatically scroll to the top on webkit-based browsers such as Chrome

This was my original query here I've been attempting to recreate the auto-grow functionality showcased in their interactive playground My approach involved adding a scrolling container and setting specific heights for elements, however, You can als ...

Tips for handling Firebase JS SDK errors within try-catch blocks

Attempting to type the err object in a function that saves documents to Firestore has been challenging. async function saveToFirestore(obj: SOME_OBJECT, collection: string, docId: string) { try { await firebase.firestore().collection(collection).doc( ...

Prevent unsaved changes on Telerik MVC website batch editing grid upon closing the window

I am currently working on a webpage in ASP.Net MVC3 with Razor engine. I have implemented Telerik MVC Grid batch editing on this page, and I am using the onDataBinding event to ensure that users save their changes before moving to the next page. However, I ...

Inspect every div and perform an action if the criteria are met

I need assistance with adding text inside a specific div based on certain conditions. Currently, all the div elements are being populated with the added text. Please review my code for more clarity on what I am trying to achieve. Can you suggest the most e ...

Are the module options in tsconfig referring to the 'SystemJS' module loader system?

When configuring a tsconfig.json file, one option that can be entered as the value for the compilerOptions 'module' property is: System This results in the following format: { "compilerOptions": { "module": "System", ... Is the &ap ...

Issue with the save-button in inlineNav of JQGrid not functioning properly after adding a second row for free

We have encountered an issue with adding new rows to several Free JQGrids. When clicking on the ADD icon in inlineNav, a new row appears and clicking the SAVE icon for the first time works correctly. However, when trying to add a second row, the Save butto ...

What is the reason for the text not being written continuously in the textfield?

Looking to create a page for collecting user information. This is a Codesandbox.io page where the issue arises. https://codesandbox.io/s/material-demo-z1x3q?fontsize=14 When I try to input "d" continuously in the 성별* textfield, I can only enter "d" ...

I am having trouble dealing with an integer AJAX response because when I try to alert it, all I get is [object, object]

$.ajax({ type: "POST", url: url_delete_admin_privilidge, data: postData, success: function(response) { console.log(response); setAdminResponse(response); alert("success") ...

Adjust the size of an image while maintaining its aspect ratio with the click of a button

Looking for guidance on maintaining aspect ratio when zooming in or out an image. I've created a basic example but struggling with keeping the aspect ratio intact. Is there a way to set a minimum size when decreasing the image? Appreciate any help ...