Reputation: 145
I found several solutions to this using jquery and javascript, however, it has to declare all the fields in jquery, but its not efficient since I have 30+ asp textboxes on my form, how can i prompt the user to save the data or changes have been made on page unload.
Upvotes: 0
Views: 240
Reputation: 157
I use this:
Be sure to set the default="" attribute on your fields!
function formIsDirty(form) {
var i, j, element, type;
if(typeof form === 'undefined') {
return false;
}
for (i = 0; i < form.elements.length; i += 1) {
element = form.elements[i];
type = element.type;
if (type === "checkbox" || type === "radio") {
if (element.checked !== element.defaultChecked) {
return true;
}
} else if (type === "hidden" || type === "password" || type === "text" || type === "textarea") {
if (element.value !== element.defaultValue) {
return true;
}
} else if (type === "select-one" || type === "select-multiple") {
for (j = 0; j < element.options.length; j += 1) {
if (element.options[j].selected !== element.options[j].defaultSelected) {
return true;
}
}
}
}
return false;
}
$( window ).unload(function() {
if(formIsDirty(document.forms["formName"])) {
return confirm("There are unsaved changes, leave this page?");
}
}
As an extra tip, when you generate the page in asp, if you set the default="" attribute to the current value in the database, you can detect not only if it's empty, but if the value has been changed.
This also allows proper use of the form.reset() button/method (w3Schools page here
Upvotes: 1
Reputation: 102
Assuming that all text text boxes have the same style class ('inputField' is used below) you can use something like:
$( window ).unload(function() {
if ($('.inputField').is(':empty')){
alert('Please fill all text boxes');
}
});
Upvotes: 1