first time question…
This link on my page
<a onclick="$('#mainbody').load('pages/login.php', tester());">Login</a>
generates this form
<form id="form">
<b>Email Address:</b> <input type="email" name="usrEmail" placeholder="email address" required><br />
<b>Password:</b> <input type="password" name="usrPass" placeholder="password" required><br />
<input type="submit" value="Log in">
</form>
my .js contains this;
function tester(){
$("#form").submit(function() {
alert('Handler called.');
return false;
});
}
…and nothing happens when the form is submitted.
However, if I change the link to
<a onclick="$('#mainbody').load('pages/login.php', function(){$( '#form' ).submit(function() { alert('Handler called.'); return false;});});">Login</a>
…this works perfectly.
Functionally I can’t see any difference between calling a named function or defining in the callback itself, but obviously the browser can!
What am I doing wrong? Is it syntax? Timing?
Or – and I’m still finding my way with jQuery – is it because even though I’m calling an eventhandler that references #form AFTER it exists, the fact the function was created first ignores it?
Yes. You should look into the jQuery delegate method.
If you say
It will work after its been loaded from a different source.