0

I have a form where I first do a validation, then submit it via ajax, where some of the fields are checked, such as a user name, which might already exist in the database. I want to display either of these error conditions right after the element in question. The form elements look like this:

  <span class="inputRow">
    <span class="formLabel">
        <label for="user_name">User Name</label>
    </span>
    <span class="formInput">
        <input id="user_name" name="user_name" class="inputText required" title="User Name" tabindex="3" type="text" value="<?= $user_name ?>" >
        <span class="formError"><span id="user_msg"></span></span>
    </span>
  </span>

I have a typical validation / errorPlacement code like this:

  errorPlacement: function(error, element) 
  {
    if (element.attr("name") == "user_name" )
        error.insertBefore("#user_msg");
    else
        error.insertAfter(element);
  },
});

To submit the form, I have a submit handler that looks like this:

submitHandler: function(form) {

  $.ajax({
    type:'POST', 
    url: 'add_user.php', 
    data:$('#reg_form').serialize(), 
    success: function(response) {
      if (response.status == "error") {
        if (!response.hasOwnProperty('user_name'))
          $("#user_msg").text("");
        else if (response.user_name.length > 0)
          $("#user_msg").text(response.user_name);
      }
    }
  });
},

The response returned is a JSON array, and I can get the error message out just fine. This all works great the first time I submit the form. If I have a duplicate user name, that is displayed properly, or if no user name is input, that is displayed properly too. The problem comes when I submit the form and get a response about a duplicate user name on file. Then if I clear the user_name field and try to submit the form again, the duplicate user name message stays there, and the message saying that a user name is required is displayed also.

To me, it seems as there is a conflict in how these are displayed because the errorPlacement function uses error.insertBefore("#user_msg"), but the return from ajax function uses $("#user_msg").text(). So the insertBefore() does not remove the previous text() values, but I haven't found any other way to display the text from errorPlacement. Can we just get the text value from the error object? If so, how? Or is there a better way to make both of these work more in the same way?

4

2 回答 2

0

我没有得到你的问题到底是什么。

如果您在发生错误时显示这样的错误时遇到问题并且您修复了它,错误仍然存​​在,这是因为您根本没有清空错误放置。在您发送新请求之前,解决方案就在这里,让您的错误位置为空。

您可以使用 jquery Dialog 以替代方法显示错误。

于 2013-02-14T03:26:33.820 回答
0

引用: “我们可以从错误对象中获取文本值吗?如果可以,如何?”

error您可以通过以下方式从对象中获取文本:

error.text()

根据您使用它的方式,您可能需要像这样格式化它:

$(error).text()
于 2013-02-14T04:03:56.940 回答