mutliple onsubmit handlers for multiple forms
I'm writing a bolt-on bit of javascript which is intended t开发者_高级运维o capture information when a form is submitted. I need to accomodate the scenario where there may be multiple forms on a web page, none/some/all of which may already have onsubmit handlers defined....and I need to fire the original handler after calling the bolt-on code.
I've got a test case setup with 2 forms, the first has no onsubmit handler, the second a simple alertbox.
I tried the code below - but that seemed to copy the pre-existing handler from form2 into form1:
window.onload=pageinit;
function pageinit()
{
for (var x=0; x < document.forms.length; x++) {
var origSubmit=document.forms[x].onsubmit;
if (typeof origSubmit != 'function') {
document.forms[x].onsubmit=dosubmit;
} else {
document.forms[x].onsubmit = function (event) {
dosubmit(event);
return origSubmit(event);
}
}
}
}
function dosubmit(ev)
{
alert('bolt-on invoked from ' + ev.target.name);
}
Any ideas?
TIA
I don't really get what you want to do, but you have the typical function in loop definition problem:
At the the time when any document.forms[x].onsubmit
function is called (obviously after the loop finished), origSubmit
in each handler will point to the same function (document.forms[document.forms.length - 1].onsubmit
). You have to "capture" the value of origSubmit
because JavaScript has only function scope, not block scope:
for (var x=0; x < document.forms.length; x++) {
var origSubmit=document.forms[x].onsubmit;
if (typeof origSubmit != 'function') {
document.forms[x].onsubmit=dosubmit;
} else {
document.forms[x].onsubmit = (function(func) {
return function (event) {
dosubmit(event);
return func(event);
}
}(origSumbit));
}
}
See also Closures for Dummies, Example 5
I think the issue may be your origSubmit
variable; it is 'closed' over the function you create there but it's changed by the for loop.
Try:
function pageinit()
{
for (var x=0; x < document.forms.length; x++) {
var origSubmit=document.forms[x].onsubmit;
if (typeof origSubmit != 'function') {
document.forms[x].onsubmit=dosubmit;
} else {
document.forms[x].onsubmit = createSubmitHandler(origSubmit);
}
}
}
function dosubmit(ev)
{
alert('bolt-on invoked from ' + ev.target.name);
}
function createSubmitHandler(origSubmit)
{
return function(event) {
dosubmit(event);
return origSubmit(event);
}
}
精彩评论