在表单提交后使用jquery更改div中的文本

时间:2013-01-02 18:03:46

标签: jquery

编辑我发布此消息后不久就意识到了我的错误。 append应为html()text()

部分代码:

<script type="text/javascript" language="javascript">
        $(document).ready(function(){
            $('#resetpassword').validate(
            {rules: {
                secretAnswer: {
                    required: true
                }
            },

            messages: {
                secretAnswer: {
                    required: "Please answer your security question"
                }
            },
            submitHandler: function(form){
                $.post("../BackgroundOperations/resetpassword.php",
                    $('#resetpassword').serialize(),
                    function(data){
                        if(data.status == 0){
                            $('#message').append("<span class='error'>Error: " + data.message + "</span>");
                        }
                        else{
                            $('.container').hide();
                            $('.short_explanation').hide();
                            $('#message').text(data.message);
                        }
                    },
                "json");
            }
            });
        });
    </script>
</head>
<body>

<!-- Form Code Start -->
<div id='fg_membersite'>
<form id='resetpassword' method='post' accept-charset='UTF-8'>
<fieldset >
<legend>Reset Password</legend>

<div class='short_explanation'>* required fields</div>
<input type='text'  class='spmhidip' name='<?php echo $vm->GetSpamTrapKey(); ?>' />

<div id="message"></div>
<div class='container'>
    <label for='emailAddress' >Email Address:</label><br/>
    <input type='text' name='emailAddress' id='emailAddress' maxlength="100" readonly="true" value="<?php echo $vm->GetEmailAddress() ?>" /><br/>
</div>
<div class='container'>
    <label for='secretQuestion' >Security Question:</label><br/>
    <input type='text' name='secretQuestion' id='secretQuestion' value='<?php echo $vm->GetSecretQuestion() ?>' maxlength="100" readonly="true" width="100" /><br/>
</div>
<div class='container'>
    <label for='secretAnswer' >Answer:</label><br/>
    <input type='text' name='secretAnswer' id='secretAnswer' maxlength="50" /><br/>
</div>
<div class='container'>
    <input type='submit' name='Submit' value='Submit' />
</div>

</form>

我正在测试无效输入(错误的安全性答案)。当我提交错误答案并提交表单时,<div id="message">会更新错误消息,但如果我一直提交无效数据,<div id="message">会保留旧错误消息,并在最后添加新消息只有一条消息。

1 个答案:

答案 0 :(得分:2)

而不是

$('#message').append("<span class='error'>Error: " + data.message + "</span>");

使用

$('#message').html("<span class='error'>Error: " + data.message + "</span>");