Thursday, October 5, 2023
 Popular · Latest · Hot · Upcoming
167
rated 0 times [  173] [ 6]  / answers: 1 / hits: 129754  / 15 Years ago, tue, april 28, 2009, 12:00:00

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 replaced 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.nnIs 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.nnIs the script included?);
return false;
}
} );


Suggestions on possibly how to do this better?


More From » typeof

 Answers
8

I'm replacing a submit button with an
anchor link. Since calling
form.submit() does not activate
onsubmit's, I'm finding it, and
eval()ing it myself. But I'd like to
check if the function exists before
just eval()ing what's there. – gms8994




<script type=text/javascript>
function onsubmitHandler() {
alert('running onsubmit handler');
return true;
}
function testOnsubmitAndSubmit(f) {
if (typeof f.onsubmit === 'function') {
// onsubmit is executable, test the return value
if (f.onsubmit()) {
// onsubmit returns true, submit the form
f.submit();
}
}
}
</script>

<form name=theForm onsubmit=return onsubmitHandler();>
<a href=# onclick=
testOnsubmitAndSubmit(document.forms['theForm']);
return false;
></a>
</form>


EDIT : missing parameter f in function testOnsubmitAndSubmit



The above should work regardless of whether you assign the onsubmit HTML attribute or assign it in JavaScript:



document.forms['theForm'].onsubmit = onsubmitHandler;

[#99637] Wednesday, April 22, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
karyme

Total Points: 545
Total Questions: 102
Total Answers: 120

Location: French Polynesia
Member since Tue, Jul 7, 2020
3 Years ago
karyme questions
Fri, Feb 18, 22, 00:00, 2 Years ago
Thu, Jul 2, 20, 00:00, 3 Years ago
Mon, Mar 9, 20, 00:00, 4 Years ago
;