我正在使用注册表
<form role="form" id="registrationForm">
<div class="form-group">
<h2><span th:text="#{register.title}">Create account</span></h2>
</div>
<div class="form-group">
<label class="control-label" for="username" th:text="#{register.yourUsername}">Your username</label>
<input name="username" id="username" type="text" maxlength="36" class="form-control" th:placeholder="#{register.username}"/>
</div>
<div class="form-group">
<label class="control-label" for="email" th:text="#{register.email}">E-mail</label>
<input name="email" id="email" type="email" class="form-control" th:placeholder="#{register.email}"/>
</div>
...
我在服务器上验证表单,如果有错误,那么我在JSON板中返回错误列表。然后我尝试在表单上的适当位置插入错误消息。
$.ajax({
type: 'POST',
url: '/register',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(registerDTO),
success: function (result) {
console.log("SUCCESS");
window.location.replace("/signIn");
},
error: function (error) {
var obj = JSON.parse(error.responseText);
for(var i = 0; i < obj.field_errors.length; ++i) {
var objError = obj.field_errors[i];
if(objError.field === "reCaptcha") {
grecaptcha.reset();
console.log('error captcha');
}
if(objError.field === "username") {
$('#username').append('<label id="username-error" class="error" for="username">' + objError.message + '</label>');
console.log('error username');
}
}
}
});
这是一行
$('#username').append('<label id="username-error" class="error" for="username">' + objError.message + '</label>');
如何在<input name="username" .. />
之后添加标签?
答案 0 :(得分:1)
使用.after()
?
$("input[name='username']").after('<label id="username-error" class="error" for="username">' + objError.message + '</label>');
答案 1 :(得分:1)
.after()
和.insertAfter()
方法将会添加DOM。
$(target).after(elementInserted)
$(elementInserted).insertAfter(target)