Why won't my jQuery form resubmit?
So I have done this a few times and it has worked, but for some reason my form won't work this time. When I submit the form jQuery uses mail.php to do one final validation. It then either submits it or echoes the form back with errors.
So basically when I submit the form with errors, it will echo it back with the respective errors, but when I correct the values and try to resubmit, it won't resubmit.
Here's the code:
<html>
<head>
<title>Contact Form Example</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#email').keypress(function() {
p = {};
p['email'] = document.getElementById("email").value;
$("#emailcheck").load("validate_email.php", p);
});
$('#message').keypress(function() {
p = {};
p['message'] = document.getElementById("message").value;
$("#messagecheck").load("validate_message.php", p);
});
$('#mail').click(function() {
p = {};
p['email'] = document.getElementById("email").value;
p['message'] = document.getElementById("message").value;
$("#body").load("mail.php", p);
});
});
</script>
</head>
<body>
<table style="display: block;" id="body">
<form action="mail.php" method="POST">
<tr>
<td align="right">
<label for="email">Email:</label>
</td>
<td align="left">
<input type="text" name="email" id="email" />
</td>
<td id="emailcheck"></td>
</tr>
<tr>
<td align="right" valign="top">
<label for="message">Message:</label>
</td>
<td align="left">
<textarea rows="5" cols="30" name="message" id="message"></textarea>
开发者_JAVA百科 </td>
<td id="messagecheck"></td>
</tr>
<tr>
<td></td><td><input id="mail" type="submit" value="Email" onclick="return false;"/></td>
</tr>
</form>
</table>
</body>
Right here:
$("#body").load("mail.php", p);
You're replacing the entire content for #body
. That includes all the elements that you've bound callbacks to so all those callbacks are lost. That probably leaves with just onclick="return false;"
as the action for #mail
so your form is dead.
You can bind your callbacks with live
or delegate
or rebind all your handlers when you replace #body
.
You need to rebind the event handler for the button (#mail
), or just use live()
.
When you load back in the HTML, the event bound to that element is lost.
Also, p
isn't scoped to the function, therefore it would persist those properties, (had you not explicitly reassigned it to an empty object literal).
Always prefix your variable definitions with var
unless you really need an implied global (99.9% the time you do not).
精彩评论