如果PASSWORD / EMAIL字段是空的,我正在尝试向元素添加消息和css样式,但是我有问题要找到正确的元素 - “help-block”。
我做错了什么?
我的JavaScript位于SEND按钮上的事件处理程序中:
if (data.errors.password) {
$(this).closest(".modal-body").find('input[name=password]').next(".help-block").addClass('has-error');
$(this).parent(".modal-body").find('input[name=password]').next(".help-block").html(data.errors.password);
// $('#password-group').addClass('has-error'); // add the error class to show red input
// $('#password-group .help-block').html(data.errors.password); // add the actual error message under our input
}
这是HTML:
<form class="modal-content" action="#">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<!-- NAME -->
<div class="form-group">
<label for="email">EMAIL</label>
<input type="email" class="form-control" name="email">
<div class="help-block"></div>
<!-- errors will go here -->
</div>
<!-- EMAIL -->
<div class="form-group">
<label for="password">PASS</label>
<input type="password" class="form-control" name="password" >
<div class="help-block"></div>
<!-- errors will go here -->
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">CLOSE</button>
<button class="btn btn-success submit">SEND<span class="fa fa-arrow-left"></span></button>
</div>
</form>
答案 0 :(得分:0)
你真的很接近
$(this).closest(".modal-body").find('input[name=password]').next(".help-block").addClass('has-error');
...但发送按钮不是 .modal-body
中的,它位于.modal-footer
。
相反,您可以使用.modal-content
:
closest
$(this).closest(".modal-content").find('input[name=password]').next(".help-block").addClass('has-error');
示例:强>
$("button.submit").on("click", function() {
$(this).closest(".modal-content").find('input[name=email]').next(".help-block").addClass('has-error').text('testing email help');
$(this).closest(".modal-content").find('input[name=password]').next(".help-block").addClass('has-error').text('testing password help');
});
// For the example, don't actually submit
$("form").on("submit", function() {
return false;
});
&#13;
.has-error {
color: #d00;
}
&#13;
<form class="modal-content" action="#">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<!-- NAME -->
<div class="form-group">
<label for="email">EMAIL</label>
<input type="email" class="form-control" name="email">
<div class="help-block"></div>
<!-- errors will go here -->
</div>
<!-- EMAIL -->
<div class="form-group">
<label for="password">PASS</label>
<input type="password" class="form-control" name="password">
<div class="help-block"></div>
<!-- errors will go here -->
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">CLOSE</button>
<button class="btn btn-success submit">SEND<span class="fa fa-arrow-left"></span></button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;