In my application there are some create update forms exist. When user giving values into the input field of these form accidentally if user press the back button or reload button of the browser there would be a confirmation message . I have used 'window.beforeunload' event to show the alert. The alert is appearing fine. But there is some problem I am facing. Scenario-1:Sometimes the alert is appearing when there is no change happened in input field and reload the browser or press the back button. Scenario-2:Suppose user entered some value in input field and reload the browser confirmation message appears. User allow to reload the page. After reload the page if user wants to leave the page still the confirmation message is appearing. I can not understand why the message is appearing after allow the page reload. I am using the following code -
$(document).ready(function(){
//ArrElem is an array which is holding the initial value of each field when the form open
$('#dvModal').on('change paste', 'select,input,textarea', function (e) {
if (typeof ArrElem != 'undefined') {
for (var i = ArrElem.length; i--;) {
if (ArrElem[i].indexOf($(this).attr('id')) >= 0) {
if ($(this).attr('type') == "checkbox" && ($(this).is(":checked").toString() != ArrElem[i].split(',')[1]))
{
ischanged = true;
}
else if ($(this).attr('type') != "checkbox" && $(this).val() != ArrElem[i].split(',')[1]) {
ischanged = true;
}
else
ischanged = false;
break;
}
}
} else {
if ($(this).val() != $(this).data('val')) {
ischanged = true;
}
else
ischanged = false;
}
});
});
/// Using this code to display the alert when click on back,reload button of the browser
window.addEventListener("beforeunload", (e) => {
if (ischanged) {
e.returnValue = null;
ischanged = false;
return null;
}
});
Probably I am doing some mistake. If so please suggest me what wrong logic I am using here. If there are any other approach exists please suggest me. I need to implement this very common feature in my application but I am struggling.
Thanks in advance.
Soumen