Javascript event handler not firing
I have a form in a modal window using jquery.simpleModal. Since simpleModal clones the contents of the initial div to create the modal dialog, I have to rebind eve开发者_StackOverflownt handlers after the modal dialog is created. My code looks something like this:
function showForm() {
$('div.contactUs').modal({
opacity: 80,
overlayClose: true,
autoResize: true
});
var container = $('.simplemodal-container');
container.find('li.phone input').mask('(999) 999-9999');
container.find('li.comments textarea').maxChar(1000, { indicator: 'div.commentLength span' });
container.find('form').submit(function () {
try {
var form = $(this);
var action = form.attr('action');
var data = form.serialize();
$.post(action, data, function (result) {
form.html(result);
showForm();
});
} catch (e) {
alert(e);
}
return false;
});
}
However, if I open the modal dialog, then close it, then open it again, it appears that the form submit handler is not wired (opening the modal dialog a second time and clicking submit results in a full page postback, rather than the ajax handler kicking in). I have verified that the other stuff is getting re-bound (the input mask and max char limit stuff), so why is the submit handler not?
Since .submit(function(){})
is shorthand for .bind('submit',function(){})
, I think that just using .live('submit',function(){})
the first time you bind the function would fix your problem without having to rebind the function on clone. .live()
will bind an event to current elements as well as any dynamically created elements that match your selector in the future.
精彩评论