Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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. I guess according to my code that code will never be executed. What should I do to chain their method too?

No JQuery please.

like image 881
Rakesh Juyal Avatar asked Oct 23 '09 14:10

Rakesh Juyal


2 Answers

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.

like image 185
ujh Avatar answered Sep 21 '22 12:09

ujh


Note, that while the accepted answer is correct (the event handler is added, it does NOT replace the existing event handler), it might be not what the user expects:

Your event handler may be called in any order with the other event handlers. And onsubmit handlers may cancel the submission to the server. So, if you "disable" the page upon submit, you might leave the user on a page where he cannot do anything any more...

like image 20
Steffen Heil Avatar answered Sep 19 '22 12:09

Steffen Heil