How to attach an event to onSubmit event of form with chaining earlier attached methods as well?

Rakesh Juyal picture Rakesh Juyal · Oct 23, 2009 · Viewed 11.2k times · Source

Actaully my application is having hundreds of pages. Now i have to attach an event 'disablePage' on onSubmit of form. I don't want to go to each and every page and write:

<form name="frmname" onSubmit="disablePage();">

What i am doing right now is:-

excerpt from common.js file; [ included in all pages ]

/* we have to attach 'attachFormSubmit' method on onLoad event, 
   otherwise forms[0] will always be null. If there is any alternative, 
   then please suggest one */
if (window.addEventListener){   
    window.addEventListener('load', attachFormSubmit, false); 
} else if (window.attachEvent){ 
    window.attachEvent('onload', attachFormSubmit );
}

function attachFormSubmit(){
    forms = document.getElementsByTagName('Form');  
    if ( forms[0] ){  // there is only one form in all pages    
        if (forms[0].addEventListener){         
            forms[0].addEventListener('submit', disablePage, false); 
        } else if (forms[0].attachEvent){           
            forms[0].attachEvent('onsubmit', disablePage);
        }
    }
}

function disablePage(){     
    document.getElementById("pageHideDivID").style.display='inline';        
}

Till this point everything is fine, disablePage() is attached to the forms of all page.

But the problem is, if someone have already attached any method to onSubmit or onLoad then that too should be executed. And i guess according to my code that code will never be executed. What should i do to chain their method too?

No JQuery please

Answer

ujh picture ujh · Oct 23, 2009

According to Quirksmode what you are doing should actually work. It should just add your events and not replace the old ones. That's why you use addEventListener/attachEvent instead of assignment to onsubmit.