如何在输入占位符中放置Bootstrap验证器错误消息?
我尝试过errorPlacement但似乎没有效果。
$('.js-form').validator({
disable: false,
errorPlacement: function(error, element) {
if(element.length) {
element.attr("placeholder", error.text());
}
}
});
答案 0 :(得分:2)
可能的解决方案是保存占位符并处理提交按钮:
$(function () {
// save placeolders....
$('.js-form').find(':input').each(function(index, ele) {
$(ele).attr('placeholderSaved', $(ele).attr('placeholder'));
});
$('.js-form').validator({disable: true}).on('submit', function (e) {
$('.js-form').find('div.with-errors').each(function(index, element) {
var cacheEle = $(element);
var errMsg = cacheEle.find('li').text().trim();
// on error change placeholder with error message
if (errMsg.length > 0) {
cacheEle.hide().prev().attr('placeholder', errMsg);
} else {
// on success restore placeholder
cacheEle.hide().prev().attr('placeholder', cacheEle.hide().prev().attr('placeholderSaved'));
}
});
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://1000hz.github.io/bootstrap-validator/dist/validator.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-5">
<form class="js-form" data-toggle="validator" role="form">
<div class="form-group">
<label for="inputName" class="control-label">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Name" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" required>
<div class="help-block with-errors"></div>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>