开发者

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

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.addEv开发者_如何学CentListener('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.


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.


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜