JavaScript's onbeforeunload function does not seem to be functioning as intended

I've been encountering issues with implementing onbeforeunload events to alert users when they attempt to navigate away from a page with unsaved form data. Despite creating a basic page, the functionality is inconsistent. There are times when it correctly warns me about leaving or reloading the page, but other times it fails to do so, even when there are no changes in the form. I've reviewed similar queries and it seems like my approach is correct. What am I missing?

<html>
<body>

<script>

window.onload = function() { doRecord(); };
window.onbeforeunload = function() { return doCheck(); };

setTimeout( doCheck, 5000 );;

var storeValue = "";

function doRecord()
{
  var inp = document.getElementById( "theinput" );
  storeValue = inp.value;
  console.log( "Executing doRecord" );
}

function doCheck()
{
  console.log( "Executing doCheck" );

  var inp = document.getElementById( "theinput" );

  console.log( "Comparing '" + storeValue + "' to '" + inp.value + "'" );

  if ( storeValue != inp.value )
  {
    console.log( "It has changed" );
    return "Are you sure that you want to leave this page, value has changed";
  }
  else
  {
    console.log( "It's OK" );
    return null;
  }
}

</script>

<h3>Form</h3>
<form id="myform" method="post" action="process.php" onsubmit="window.onbeforeunload = null" >
<input type="text" size="20" name="sometext" id="theinput" value="Change This" />
<p>
<input type=submit />
</form>

</body>
</html>

Answer №1

It appears that there was a mistake in the code snippet provided:

<form id="myform" method="post" action="process.php" onsubmit="window.onbeforeunload = null" >

Perhaps it should be corrected to:

<form id="myform" method="post" action="process.php" onsubmit="return (window.onbeforeunload()== null)" >

After making this adjustment in my fiddle located here, the issue seems to be resolved.

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

Eliminate duplicate time slots in Laravel and Vuejs

Currently, I am delving into laravel(5.2) and vuejs as a newcomer to both frameworks. My goal is to utilize vuejs to eliminate redundant time slots. In my blade file, the code looks like this: <div class="form-group"> <label for="form-fi ...

Use the lodash chunk method to split a mapped array into two separate arrays

Looking to organize some data into tables? I have a dataset from an API that you might find helpful. [ { date: "1/11", data: [ { camera: "camera 1", count: 10 }, { camera: "camera 2", count: 20 ...

Incorporate a button into your Django formset application

Working with Django 5, I am in the process of creating a web application for managing a Secret Santa gift exchange project. One issue I'm facing is that formsets are not dynamic, meaning I cannot generate a variable number of forms based on user inpu ...

React Ant Design: Toggle Visibility of Columns

Seeking a method to toggle the visibility of columns for the Table Component in Ant Design. The goal is to include a checkbox next to each column name. When unchecked, the column should be hidden. In my previous experience with react-table, accomplishing ...

Is there a way to dynamically change an icon based on certain conditions using typescript?

I am struggling with displaying icons in my TypeScript code using Material Icons. I need to dynamically change the icon based on a condition, for example if the power is false I want to display 'power_off', but if it's true then I want to di ...

The loading cursor in IE7 flickers incessantly, causing the webpage to lag and become un

When I move my cursor and click in text fields, the page becomes unresponsive and shows a wait cursor. If you're curious to see this issue in action, check out this video. This problem is specific to IE7. I've attempted to identify any ajax re ...

The @Input decorator in Angular 2/4 is designed to only transfer fundamental values and not collections or complex data

I have encountered an issue while attempting to use @Input with a list of objects, where the @Input variable ends up being undefined. What is functioning properly can be seen in home.component.html: <p> <it-easy [mycount]="countItem" (result ...

history.push() function is ineffective within a JavaScript file that does not contain a class

I've been delving into React and encountering an issue with the history.push("/dashboard") method, it's not functioning as expected. import axios from "axios"; import { GET_ERRORS, GET_PROJECT, GET_PROJECTS } from "./types"; export const createP ...

Capture all URLs containing [...slug] and generate static props only for valid addresses in Next.js

I am utilizing dynamic routes with the fallback:true option to ensure newly created pages are accepted. First, I check if the parameters are true, then I create related props and display the component with those props. In the console, I can observe that Ne ...

SSR with Material UI Drawer encounters issue during webpack production build meltdown

When I attempted to utilize the Material UI SSR example provided by Material-UI (Link), it worked successfully. However, my next step was to integrate the Material-UI Drawer into this example. To do so, I utilized the Persistent drawer example code also pr ...

Issue: The variable 'HelloWorld' has been declared but not utilized

Why am I encountering an error when using TypeScript, Composition API, and Pug templating together in Vue 3? How do I resolve this issue when importing a component with the Composition API and using it in a Pug template? ...

Strategies for simplifying this extensive if/else block

My current if/else statement in React Native is functional but seems verbose. I am curious to know how other developers would optimize and shorten it. I feel like my code represents a beginner's approach, and I welcome suggestions on how to improve i ...

Puppeteer throwing an error when querying selectors cannot be done (TypeError: selector.startsWith is not a supported function)

I recently installed Puppeteer and ran into an issue when trying to query a selector. I keep receiving a TypeError: selector.startsWith is not a function error. I attempted to resolve the problem by tweaking the core code and adding toString(), but unfort ...

Having issues with contenteditable functionality not functioning properly on elements that are dynamically generated

Creating an unordered list dynamically and adding items to it on a button click. Appending it to a section with contenteditable set to true, but encountering issues. The code snippet below demonstrates the process: // Create text input var categoryInput = ...

How to retrieve an element by its class using JavaScript and Jquery while implementing a

I am working on creating a quiz example using Jquery, but I am facing some challenges when trying to manipulate CSS classes with hover in Jquery. .right{ background-color: white; } .wrong { background-color: white; } .right:hover { background-color ...

Managing ajax requests, failing to retrieve information

I am struggling to configure my client-side ajax calls to send data to a node express server. I want the ajax request to be triggered "onclick" of an href link. My goal is to pass the ID of the link as a variable to the server, but unfortunately, the serv ...

Unable to send information to a function (using jQuery)

I'm struggling to pass the result successfully to another function, as it keeps returning an undefined value: function tagCustomer(email, tags) { var o = new Object(); o.tags = tags; o.email = email; o.current_tags = getCustomerTags(email ...

Issues are arising with back4app's cloud code due to an invalid function being

My current challenge involves implementing a payment system in an iOS app using Conekta. Previously, everything was working smoothly with Braintree in the cloud code on Back4App, but after switching to Conekta, the Back4App calls keep failing with an "Inva ...

How can I utilize the JQuery GetJSON function to retrieve HTML content from an external webpage?

Imagine you're attempting a jQuery ajax request like this: $.ajax({ ... url: http://other-website.com ... }) You probably know that due to the same-origin policy, this request will fail because the URL is for an external domain. But the ...

Tips on transforming two same-length arrays into a single array of objects using JavaScript

I have a dilemma with two arrays that have been structured as follows: arr1 = [10, 20, 30, 40, 50]; arr2 = ['x', 'y', 'z', 'w', 'v']; My goal is to utilize JavaScript in order to transform these arrays of ...