使用jQuery提交表单,然后更新表单以显示错误,不允许再次提交表单

时间:2011-12-06 22:05:01

标签: php jquery html forms

我正在通过PHP函数显示表单:

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;
}

然后我有一个文件,这个表单通过jQuery发布到处理值。如果处理器发现错误,它将调用getLoginForm函数并将错误数组作为其参数。这样,当表单重新显示时,错误会显示在字段下方。

问题是,处理器文件返回整个表单,并与旧表单交换,这是我认为问题所在。当我尝试再次提交表单时,它没有做任何事情,因为jQuery必须不知道这个新创建的表单。

我有什么方法可以解决这个问题?

谢谢, 莱恩

更新

jQuery提交处理程序:

$('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();
    });

1 个答案:

答案 0 :(得分:0)

尝试使用&#34; live()&#34;绑定到动态创建的对象的事件。

为此,您需要将代码更改为:

$('form').live('submit', function() { ...

使用&#34; live&#34;绑定到事件将绑定到与jQuery选择器匹配的所有当前和未来元素。由于您要覆盖表单,因此这是一个新元素,因此您当前的代码不会绑定到提交事件。