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?