About a month ago I learnt of an IE specific event, called "onBeforeUnLoad", that allows you to capture the moment a user leaves a page. Using this, I wrote an article that described how to remind a user to save if they leave a page that happens to be a document in edit mode.
What this article overlooked was that even if a form is in edit mode it may not necessarily need saving as it may not have actually been altered. Wait though, Bob Mattler has come up with a solution. We can now loop through all the fields on the form and compare them to the original values. If any fields have changed then we can use the onBeforeUnload event to remind the user to save. Otherwise there is no need to confuse them with this method.
How did Bob do it? Well, his method makes use of the Document Object Model (DOM), with which we can check whether an input's current value is the same as its original value. Consider the following table. This shows us the way we can access the current and original value for each of the different inputs types:
Input Type | Current Value | Original Value |
text | obj.value | obj.defaultValue |
textarea | obj.value | obj.defaultValue |
select-one | obj.options[x].selected | obj.options[x].defaultSelected |
select-multiple | obj.options[x].selected | obj.options[x].defaultSelected |
check-box | obj.checked | obj.defaultChecked |
radio-button | obj.checked | obj.defaultChecked |
function isFormChanged() {
var rtnVal = false;
var frm = document.forms[0];
var ele = frm.elements;
for ( i=0; i < ele.length; i++ ) {
if ( ele[i].type.length > 0 ) {
if ( isElementChanged( ele, i ) ) {
rtnVal = true;
break;
}
}
}
return rtnVal;
}
function isElementChanged( ele, i ) {
var isEleChanged = false;
switch ( ele[i].type ) {
case "text" :
if ( ele[i].value != ele[i].defaultValue ) return true;
break;
case "textarea" :
if ( ele[i].value != ele[i].defaultValue ) return true;
break;
case "radio" :
val = "";
if ( ele[i].checked != ele[i].defaultChecked ) return true;
break;
case "select-one" :
for ( var x =0 ; x <ele[i].length; x++ ) {
if ( ele[i].options[ x ].selected
!= ele[i].options[ x ].defaultSelected )
return true;
}
break;
case "select-multiple" :
for ( var x =0 ; x <ele[i].length; x++ ) {
if ( ele[i].options[ x ].selected
!= ele[i].options[ x ].defaultSelected )
return true;
}
break;
case "checkbox" :
if ( ele[i].checked != ele[i].defaultChecked ) return true;
default:
return false;
break;
}
}
alert( (isFormChanged()) ? 'Changed':'Unchanged');
Copyright © 2000 - 2024 Jake Howlett of Rockall Design ltd. This article was printed from codestore.net