0

如何将 Bootstrap 验证器错误消息放在输入占位符中?

我尝试了errorPlacement,但似乎没有效果。

jsFiddle

 $('.js-form').validator({
            disable: false,
            errorPlacement: function(error, element) {
                if(element.length) {
                    element.attr("placeholder", error.text());
                }
            }
        });
4

1 回答 1

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>

于 2016-03-30T15:29:51.647 回答