这是我的 HTML 表单。如果字段留空,我会尝试显示错误。如果留空,则只有选择字段会显示错误,而其他字段则不会。我尝试从 firebug 操作 DOM,但即使在那里,我也无法在电子邮件、密码字段中添加错误 div。
<form name="sentMessage" id="RegisForm" novalidate>
<div class="control-group form-group">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="controls">
<input type="email" class="form-control " name="email" id="email" placeholder="Email" value="{{ old('email') }}">
</div>
<div class="controls">
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
<div class="controls">
<input type="password" class="form-control" name="password_confirmation" id="re-passd" placeholder="Retype Password">
</div>
<div class="control-group form-group">
<div class="controls">
<select name="type" class="form-control" id="type">
<option value="" selected="selected">Account Type</option>
<option value="Buyer">Buyer</option>
<option value="Seller">Seller</option>
<option value="Agent">Agent</option>
</select>
</div>
</div>
<button type="submit" class="btn btn-primary">Create Account</button>
<!-- For success/fail messages -->
</div>
</form>
这是我的js代码
$(document).ready(function () {
"use strict";
$('#RegisForm').on('submit', function (e) {
e.preventDefault();
$.ajax({
method: "POST",
url: '/auth/register',
data: $(this).serialize(),
success: function (msg) {
window.location.replace('dashboard');
},
error: function (errors) {
$('.text-danger').remove();
$.each(errors.responseJSON, function (fieldName, error) {
var fieldNameArray = fieldName.split('.'),
inputName = '';
$.each(fieldNameArray, function (index, value) {
inputName += "\\[" + value + "\\]";
});
inputName = inputName.replace('\\[', '').replace('\\]', '');
$('#' + inputName ).before('<div class="text-danger">' + error[0] + '</div>');
});
}
});
});
});
在我这样做之后console.log(inputName + ' ' + error[0] );
我得到了这样的东西:
type The type field is required.
email The email field is required.
password The password field is required.
最佳答案
尝试使用名称而不是 ID 进行选择。
$("[name='"+inputName+"']")
由于像这样的奇怪行为,我通常会避免使用 ID 进行动态选择。我希望我知道有关您的情况的更多细节 - 可能有其他具有相同 ID 的元素被选中,而不是您的元素(因为 ID 应该是唯一的)。
关于javascript - 无法添加错误div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31956877/