[thelist] javascript default event handlers, default events. [TIP]

VOLKAN ÖZÇELİK volkan.ozcelik at gmail.com
Mon Aug 29 15:42:27 CDT 2005


This may be  a bit long for a tip.
Thought it might be helpful anyways.

<tip author="Volkan OZCELIK" type="javascript form validation">

Often we tend to validate form on the onsubmit event handler in a
global js page.

Let us write some unobstrusive semi-pseudo code and demonstrate it:

<script type="text/javascript">
function init(){
   var objForm=document.getElementById("FrmPage");//the form element

   if(typeof(document.addEventListener)!="undefined")
        objForm.addEventListener("submit",FrmPage_submit,false);
   else if(typeof(document.attachEvent)!=undefined)
       objForm.attachEvent("onsubmit",FrmPage_submit);   

   // I did not use 
   //      objForm.onsubmit=FrmPage_submit 
   // on purpose.
   //
   // We will come to that later.
}
window.onload=init;

function FrmPage_submit(evt){
   var blnError = ... control if my fields contain any error
   such as an invalid e-mail and if so set this to true.

   if(blnError) alert(the error message);

   return !blnError;//so if blnError is set to true the method will
return false.
                         //at this point the form should not be
submitted -ideally-.
}
</script>

In IE, the scenario will be as expected: if there is a validation
error; a message will be alerted, the method will return false and
form FrmPage will NOT be submitted.

However in Firefox, Mozilla, Netscape and Opera (i.e. the rest of the
world) THE FORM WILL BE SUBMITTED even when FrmPage_submit function
returns false.

This is because in Mozilla there is the default event handler for the
submit event which we have not overridden.

To resolve it, just change this

   if(typeof(document.addEventListener)!="undefined")
        objForm.addEventListener("submit",FrmPage_submit,false);
   else if(typeof(document.attachEvent)!=undefined)
       objForm.attachEvent("onsubmit",FrmPage_submit);   

to

   document.getElementById("FrmPage").onsubmit=function(){return false;};

   if(typeof(document.addEventListener)!="undefined")
        objForm.addEventListener("submit",FrmPage_submit,false);
   else if(typeof(document.attachEvent)!=undefined)
       objForm.attachEvent("onsubmit",FrmPage_submit);  


and everything will work as expected: 

in both ie and mozilla if there is a validation error form will NOT be
submitted.


Having seen it, take the Occam's razor from your bag and convert the
code soup above to

   document.getElementById("FrmPage").onsubmit=FrmPage_submit;

just a single line and it works as expected as well.

Moral of the story:
Take the simplest solution whenever possible. The simplest possible
solution is most of the timethe optimum solution, or is a solution
with the highest proximity to truth.

</tip>


More information about the thelist mailing list