I am working with a MVC4 project. I have an edit page where I allow users to add items to a HTML table. When items are added and not saved, I use a window.onbeforeunload to warn the user when trying to leave the page. Everything is working out expect the case where I only delete one item from the table, my window.onbeforeunload = null; triggers. I only want it to trigger when ALL items are removed.
Code examples:
$("#AddLinkDiv a").on("click", function () {
$.ajax({
url: "../../DrugArticles/EditHandledPropertiesRow/" + $("#NplPackId").val(),
cache: false,
success: function (data) {
$("#EditDrugArticleTable tr").last().after(data);
$("#EditDrugArticleTable tr").last().addClass("ToBeAdded");
window.onbeforeunload = function() {
return 'Are you sure you want to leave?';
};
addDatePicker();
},
dataType: "html"
});
return false;
});
...
if ($("#EditDrugArticleTable .State[Value='New']").find("tr").length == 0) {
window.onbeforeunload = null;
}
...
$("#EditDrugArticleTable").on("click", "td.Delete a", deleteRow);
...
function deleteRow() {
var parentRow = $(this).parent().parent();
var state = parentRow.find("input.State").val();
if (state == "Existing") {
parentRow.addClass("ToBeDeleted");
parentRow.find("input").not("[type='hidden']").prop("disabled", true);
parentRow.find("input.State").val("Deleted");
$(this).toggleClass("backStage");
$(this).attr("title", "Ångra");
window.onbeforeunload = function() {
return 'Are you sure you want to leave?';
};
}
else if (state == "Deleted") {
parentRow.removeClass("ToBeDeleted");
parentRow.find("input").prop("disabled", false);
if (!parentRow.find("input.Procured").is(":checked")) {
parentRow.find("input.Price").prop("disabled", true);
}
parentRow.find("input.State").val("Existing");
$(this).toggleClass("backStage");
$(this).attr("title", "Ta bort");
if ($("#EditDrugArticleTable").prop(".State[Value='New']")) {
window.onbeforeunload = null;
}
}
else if (state == "New") {
parentRow.remove();
if ($("#EditDrugArticleTable").prop(".State[Value='New']")) {
window.onbeforeunload = null;
}
}
return false;
}
Thanks in advance.
Try use this: $(window).unbind("beforeunload"); - when you need to undind event
$(window).bind("beforeunload", function() { ... }); - or this, when you need to get it back
Be careful using this event. Opera doesn't handle onbeforeunload, or i don't know hot to do it.
After last comment I think it must look like this:
function ckeckUnloadEvent() {
if ($("#EditDrugArticleTable .State[Value='New']").find("tr").length == 0) {
window.onbeforeunload = null;
}
else {
window.onbeforeunload = function() {
return 'Are you sure you want to leave?';
};
}
}
Your function:
var parentRow = $(this).parent().parent();
var state = parentRow.find("input.State").val();
if (state == "Existing") {
...
}
else if (state == "Deleted") {
...
}
else if (state == "New") {
...
}
ckeckUnloadEvent();
return false;