Reputation: 13
I'm baffled by this. I cannot get this to work. This first block will display the login form, but the submit event will not be caught:
function appInit() {
$.post(clubapp,function(d){
if ( d == "failure:nolog" ) { $("#shell").html(loginform); }
});
}
appInit();
$("#loginform").submit(function(e){
alert("x"); // Does not alert
});
But if the login form is created outside of the $.post it works as expected.
function appInit() {
$.post(clubapp,function(d){
if ( d == "failure:nolog" ) { j = 1; }
});
if ( j == 1 ) { $("#shell").html(loginform); }
}
appInit();
$("#loginform").submit(function(e){
alert("x"); // catches and alerts "x"
});
This seems a terribly inelegant workaround, and wondering why it won't work inside the post action.
EDIT: I erred in stating the 2nd one works. I stripped out debugging code to ask the question, but a pair of alerts to show the value of j before and after "if ( j == 1 )" caused this to work somehow. Removing those alerts made it fail.
Upvotes: 1
Views: 725
Reputation: 24638
Using using a delegated submit event is the best way to bind event handlers to future events. You don't have to worry about remembering to fire the code once the dynamic content is added.
$(function() {
$(document).on("submit", "#loginform", function(e){
alert("x"); // catches and alerts "x"
});
});
The advantage with this is that it works both for existing elements and future (yet-to-be-added) elements.
Upvotes: 3
Reputation: 3527
It doesnt work becouse in first case you create html form after you have set event listener, so there is no form yet when you try to set the listener. Callback function to $.post fires when ajax request is completed and it' definetely happens after you have tried setting the listener.
Just put your listener in same callback function and it will work fine:
function appInit() {
$.post(clubapp,function(d){
if ( d == "failure:nolog" ) {
$("#shell").html(loginform);
//listener
$("#loginform").submit(function(e){
alert("x"); // Will alert
});
}
});
}
Upvotes: 0