I have several forms which look like this:
<form id=myForm onsubmit="saveFormData(this);return false">
....
</form>
Upon submission, a custom function is executed and the default action (sending the data through http) is canceled.
But now I need to validate the form and if it validates ok, then trigger the custom function (saveFormData in this case, but it may be different for other forms), otherwise do nothing.
So the final event handler should work like this:
$('#myForm').submit(function(){
if(formValidatesOk(this))
saveFormData() ;
return false ;
}
However, I cant make changes to the HTML code, so I need a general way of redefining the onsubmit event by wrapping the hardcoded handler with a jquery event handler.
The first thing that comes to my mind is something like (untested):
var hardcodedHandler = $('#myForm').prop('onsubmit') ; // save the current handler
$('#myForm').prop('onsubmit',null) ; // remove the current handler
$('#myForm').submit(function(){
if(formValidatesOk(this)) // if the form is valid then...
Function(hardcodedHandler).call(this) ; // trigger the original handler
return false ;
}) ;
But that’s not very elegant (to say the least).
Do you know of a better way of doing it?
You can just take the old function from the
onsubmitproperty of the element, you don’t need toevalit:Demo at jsfiddle.net