Tuesday, November 27, 2007

JavaScript : Validation (Checking for all controls in that Page)

// Code to pop up a warning if user changes anything in the page and leaves the page
// Picked up from http://www.codestore.org.
// Known to work only on IE 5+ (most of the time)
var isDocBeingSubmitted = false;

function isFormChanged()
{
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 ) )
if ( isElementChanged( ele[i]) )
{
return true;
}
}
}
return false;
}
function isElementChanged( elem )
{
var isValidationEnabled = true; //validate all controls by default

//to avoid some controls to be checked for changes
if (elem.Validate)
{
if (elem.Validate == "false")
isValidationEnabled = false;
}


if (isValidationEnabled)
{
switch ( elem.type )
{
case "text" :
if ( elem.value != elem.defaultValue ) return true;
break;

case "textarea" :
if ( elem.value != elem.defaultValue ) return true;
break;
case "radio" :
if ( elem.checked != elem.defaultChecked ) return true;
break;
case "select-one" :
for ( var x =0 ; x <elem.length; x++ )
{

if ( elem.options[ x ].selected != elem.options[ x ].defaultSelected )
{
//to avoid facility and department drop down change throwing the alert box
if(elem.name != "FacilityDropDownList" && elem.name != "DepartmentDropDownList")
return true;
}
//if you didnt set the selected to default, and user clicks cancel, dropdown will
//show the last changed value. If user saves the data, it will lead to error.
//So, we are changing the value back to default value irrespective of user click(ok/cancel).
if( elem.name == "FacilityDropDownList" || elem.name == "DepartmentDropDownList")
elem.options[ x ].selected = elem.options[ x ].defaultSelected;
}
break;
case "select-multiple" :
for ( var x =0 ; x <elem.length; x++ ) {
if ( elem.options[ x ].selected != elem.options[ x ].defaultSelected ) return true;
}
break;
case "checkbox" :
if ( elem.checked != elem.defaultChecked ) return true;

default:
break;
} //switch
}// if (isValidationEnabled)
return false;
}