I need to test whether the value of a form's onsubmit
is a function. The format is typically onsubmit="return valid();"
. Is there a way to tell if this is a function, and if it's callable? Using typeof just returns that it's a string, which doesn't help me much.
EDIT: Of course, I understand that "return valid();" is a string. I've replace
d it down to "valid();", and even "valid()". I want to know if either of those is a function.
EDIT: Here's some code, which may help explain my problem:
$("a.button").parents("form").submit(function() {
var submit_function = $("a.button").parents("form").attr("onsubmit");
if ( submit_function && typeof( submit_function.replace(/return /,"") ) == 'function' ) {
return eval(submit_function.replace(/return /,""));
} else {
alert("onSubmit is not a function.\n\nIs the script included?"); return false;
}
} );
EDIT 2: Here's the new code. It seems that I still have to use an eval, because calling form.submit() doesn't fire existing onsubmits.
var formObj = $("a.button").parents("form");
formObj.submit(function() {
if ( formObj[0].onsubmit && typeof( formObj.onsubmit ) == 'function' ) {
return eval(formObj.attr("onsubmit").replace(/return /,""));
} else {
alert("onSubmit is not a function.\n\nIs the script included?");
return false;
}
} );
Suggestions on possibly how to do this better?
Try
You can try modifying this technique to suit your needs:
Make sure you are calling typeof on the actual function, not a string literal:
Well,
"return valid();"
is a string, so that's correct.If you want to check if it has a function attached instead, you could try this:
I think the source of confusion is the distinction between a node's attribute and the corresponding property.
You're using:
You're directly reading the
onsubmit
attribute's value (which must be a string). Instead, you should access theonsubmit
property of the node:Here's a quick test:
This yields:
A simple check like this will let you know if it exists/defined: