I’m displaying a form via a PHP function:
function getLoginForm($errors = false) {
$output .= '<form action="#" name="login" method="post" />';
$output .= '<h2>Sign in to ' . APPNAME . '</h2>';
$output .= '<div class="field">';
$output .= '<label for="username">Username</label>';
$output .= '<input type="text" id="username" name="username"' . getPostValue('username') . ' />';
if(isset($errors['username'])) {
$output .= '<div class="help">' . $errors['username'] . '</div>';
}
$output .= '</div>';
$output .= '<div class="field">';
$output .= '<label for="password">Password</label>';
$output .= '<input type="password" id="password" name="password"' . getPostValue('password') . ' />';
if(isset($errors['passsword'])) {
$output .= '<div class="help">' . $errors['username'] . '</div>';
}
$output .= '</div>';
$output .= '<div class="message"></div>';
$output .= '<div class="button">';
$output .= '<button type="button" name="commit">Login</button>';
$output .= '</div>';
$output .= '</form>';
return $output;
}
I then have a file that this form posts to via jQuery to process the values. Should the processor find an error, it will call the getLoginForm function with an error array as its parameter. That way, when the form redisplays, the errors show up beneath the fields.
The thing is, the processor file returns the entire form and it gets swapped out with the old form, which is where I think is the problem is. When I try to submit the form again, it doesn’t do anything, because jQuery must not know about this newly created form.
What are my options for solving this issue?
Thanks,
Ryan
UPDATE
jQuery submission handler:
$('form').submit(function(e){
var formElement = $(this);
var data = formElement.serialize();
var page = 'process.php?p=' + formElement.attr('name');
formElement.find('button[name=commit]').attr('disabled', 'disabled').addClass('disabled');
formElement.find('.message').html('<div class="pending">Sending your request... please wait...</div>');
$.post(page, data, function(response) {
formElement.html(response);
});
e.preventDefault();
});
Try using “live()” to bind to events for dynamically created objects.
To do this, you would change your code to:
Using “live” to bind to events will bind to all current and future elements matching the jQuery selector. Since you are overwriting your form, this is a new element and your current code will not bind to the submit event as a result.