binding form submit event on a "dynamically" created form
I am creating a "dynamic form" with jquery.append( '<form id = "dyn_form" action='' method='POST'....') .
The form.submit( function( event ) {} ) does not bind the submit event handler immediately after the append returns.
However, if I call the form.submit( ... ) after a random 1/2 second delay the submit event handler is bound correctly.
Currently my code looks like this,
$('#form_container').append( '<form id = "dyn_form" action='' method='POST'....');
if( $('#dyn_form').length ) {
$('#dyn_form').submit( function(event) ) {
...
}
}
else
{
setTimeout( bind_form(), 500); // bind_form does the submit event handling
}
My guess is that there is a delay between the append and when the form element is available in the doc tree??
Is there a better way to handle this (maybe a callback) as setTimeout() seems "hacky" / unpredictable and slows down the page?
Thanks,
-Senthil