我有一个Bootstrap模式,您可以在其中选择日期.在后台,隐藏的字段填充,也提交与表单.
问题是当您选择datepicker元素时,它会删除一些奇怪原因的隐藏值(但仅包含由Javascript填充的隐藏值).
Datepicker JS:
var date = new Date(); date.setDate(date.getDate()); $('#datepicker').datepicker({ format: "dd/mm/yyyy",startDate: date,autoclose: true,});
隐藏字段填充JS:
$(function () { $('#appointment').on("show.bs.modal",function (e) { $("#request_id").val($(e.relatedTarget).data('request-id')); }); });
隐藏HTML元素:
<input type="hidden" name="request_id" id="request_id" value="">
当模态框最初弹出时,我可以看到隐藏的值字段被填充,但是当我点击日期戳,它被删除.为什么是这样?
解决方法
问题是当打开引导程序datepicker时,show.bs.modal被触发.因此,只有当show.bs.modal与模态打开相关时,才需要设置#request_id值.您可以使用一种方法来获取触发事件的元素,即检查处理程序中的e.target.id值.
这里有一个工作示例:
$('#datepicker').datepicker({ format: "dd/mm/yyyy",startDate: new Date(),}); $(function () { $('#appointment').on("show.bs.modal",function (e) { if( e.target.id == 'appointment'){ $("#request_id").val($(e.relatedTarget).data('request-id')); } }); });
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/> <link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker3.css" rel="stylesheet"/> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script> <input type="hidden" name="request_id" id="request_id" value=""> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#appointment" data-request-id="myExampleId"> Open appointment modal </button> <div id="appointment" class='modal fade'> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class='modal-header'> <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button> <h4 class="modal-title">Title</h4> </div> <div class="modal-body"> <div class="form-group"> <label for="datepicker">Date bootstrap</label> <input type="text" id="datepicker"> </div> </div> </div> </div> </div>