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

旧街凉风 提交于 2019-12-22 08:10:09

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/1613744/how-to-attach-an-event-to-onsubmit-event-of-form-with-chaining-earlier-attached

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!