Tips for notifying a user about leaving a page without saving their information

I created a small table where users can input product names and numbers. My question is, how can I notify the user if they try to leave the page without saving the entered information?

<form action="index.php" method="post">
<input type="text" name="pnumber" value="" placeholder="Product Number...."/> 
<input type="text" name="pname"   placeholder="Product Name...." /> <br>
<button id="save">save</button>
</form>

Answer №1

Contemporary web browsers have integrated the window.onbeforeunload event that can be utilized to implement such features.

Answer №2

To start off, you can verify if the fields are empty.

$(window).unload(function() {
    var phoneNumber = $("input[name=phoneNumber]").val();
    var personName = $("input[name=personName]").val();

    if(phoneNumber === "" || personName === "") {
        alert("Please complete the form");
        return false;   
    }
});

Another method is to use a global flag for checking.

var isSaved = false; // global variable

$("#save").click(function() {
   isSaved = true;
});

$(window).unload(function() {
    if(isSaved === false) {
        alert("Please complete the form");   
        return false;
    } 
});

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

What steps can I take to prevent automatic redirection when submitting an input on an AJAX form in PHP?

I have encountered a strange issue with my HTML post loading dynamically inside a modal popup. I noticed that when I submit the form directly in the post, it works fine but doesn't work inside the modal :/ Every time I try to submit the form from the ...

Events are not being emitted by Socket.io

I recently started learning about socket.io and began following a tutorial on the socket.io website. I have installed everything correctly, but it seems that the socket is unable to emit the event in the index.html file. Can anyone help me with this? Here ...

Tips for displaying information from two separate MongoDB documents on a single webpage with the help of Mongoose and Express

Currently, I am working with NodeJS, Express, EJS, and Mongoose. While I have a good grasp on most of these technologies, I find myself navigating through the complexities of Mongoose. In my project, I have established two Models that are interconnected w ...

Troubleshooting jQuery ajax data retrieval issue in Internet Explorer 8

I'm currently utilizing jQuery submit to submit form data and retrieve it. The data is returned via ajax. When the data is received, I want to display the DIV Gallery HTML. To do this: <form action="" method="post" name="view_all" id="view_all" ...

Is it possible for javascript to show the user's current location on a google map without using a KML layer?

I need help with loading a KML file using JavaScript and adding a marker to the map at the user's current location. The code I have been working on works fine, but it seems to be missing the geolocation check for the current position. How can I proper ...

What is the best way to halt an event using jQuery?

My question is about handling events on a webpage. I am interested in triggering a jquery method when the user clicks a link to navigate away from the page. In this method, I need to perform some checks before allowing the user to leave, so I plan to use: ...

Using the radius to determine the center point of the circle

<span class="qs">Q{{i + 1}} <a href="#question-view"></a></span> <div class="tooltipp text-center bubble[ngStyle]="bubbleStyle(prof?.proficiencyBrightness, prof?.proficiencyRadius)"> </div> In the illustration below, ...

Combine two arrays that have been transformed using mapping in JavaScript

Is there a way for me to utilize the useState hook in order to save and combine two arrays? I have managed to individually fetch and store values from the one and two arrays, but I am struggling to concatenate them into a single array. My ultimate goal i ...

Swapping the non-DOM element text with another content

Currently facing an issue in my project where I need to replace plain text inside a contenteditable element without being enclosed in a DOM element. Here, I'm extracting the textNode using window.getSelection(); and looking to perform a text replaceme ...

Bootstrap Toggle Button with Dropdown Menu

I have a button-group with font awesome icons and a dropdown on one of them, as illustrated in the example below. I am trying to toggle the button status, but for some reason, the 'active' class is automatically removed on mouseout. It seems to ...

Select the default option and what occurs in the event of an HTTP connection

I am currently facing an issue with two aspects. Firstly, I am struggling to set a default option in my Select element. Despite using ng-model, it only displays a blank option at the moment: <select class="form-control" ng-model="pageSize"> ...

Utilizing a functional component to incorporate a "load more" button in ReactJS

Hey everyone, I've come across this ReactJS code that I need some help with: function DisplaySolutions({solutions}) { const topSolutions = solutions.slice(0, 4); const remainingSolutions = solutions.slice(4); const [isD ...

Issue with Component not displaying properly upon refreshing

I'm currently using react.js and I have a button with an onClick event. My goal is to reload the page after clicking the button and then display a specific component on the page. However, I've encountered an issue where the component doesn't ...

Excess padding in Internet Explorer 7 when a table is nested within a div tag

I have exhausted all potential solutions found on the internet and still cannot seem to solve this issue. Here is an example page that highlights the problem: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/l ...

Perform an ajax request to check for the existence of an image and insert

I've been trying to implement asynchronous JavaScript based on guidance from this answer, but I'm facing some difficulties in understanding where things are going wrong. My goal is to use autocomplete functionality to request specific files from ...

Enhancing image search functionality through dynamic HTML updates

I need help figuring out how to update the link address for profile pictures on my NHL stats website. Currently, I am using a script to append the image to the body, but I don't know how to properly add the player ID ({{p1_ID}}) to the link and includ ...

How come I am unable to pass JavaScript values to my PHP5 code?

I'm struggling with this code snippet: <?php $html=file_get_contents('testmaker_html.html'); echo $html; ?> <script type="text/javascript"> document.getElementById('save_finaly_TEST').addEventLis ...

The styles defined in CSS do not have an impact on EJS templates that have GET route paths stacked

I have a CSS file located in the public directory and two EJS templates in the views directory. The CSS file works fine when using this route: app.get('/theresa', (req, res) => { res.render('templates/home') }) However, when I ...

Indicate the end of the row in JavaScript when using the match() function

What's the best way to identify the end of a row when using the match() function? I'm trying to extract "2021 JANUARY 18 MONDAY" from this page. https://i.sstatic.net/bTNdQ.png https://i.sstatic.net/YzFs2.png If there is additional text after ...

The search functionality on my website, powered by webapp2 and HTML, is not functioning properly

Upon examination, I noticed that my search term is being transmitted to my handler as an empty string. Here are the key components: This is my HTML form: <form class="navbar-search" action="/search"> <input type="text" class="se ...