如果未选择日期,如何防止 bootstrap-datepicker 从输入中清除现有值?
我有一个用 php 预填充用户出生日期的 div:
<label for="dob">出生日期</label><input type="text" class="form-control" id="dob" name="dob" value="<?php $date = new DateTime($this->swimmers->dob);echo $date->format('d/m/Y');?>"><span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
javascript:
Bootstrap 已设置并正常工作,但是,当dob"输入在没有进行日期选择的情况下获得和失去焦点时,它会清除预先填充的值.
但是,如果通过日期选择器选择了日期,然后输入获得和失去焦点,则不会发生这种情况.
如果有人点击,如何将预先填充的值保留在字段中?
第一次选择日期时,它会清除预先填充的值,但在您第二次选择日期之前不会插入所选日期.
更新:工作代码更新!
解决方案没有更多的例子无法确定,但问题可能在于 $this->swimmers->dob代码> 您提供给输入的字符串未被 bootstrap-datepicker 识别为日期格式.您可以通过将
data-date-format
属性添加到您的输入来定义它使用的日期格式.
例如,如果您使用的是 MySQL 格式的日期或 PHP 的 DateTime 对象和 $date->format('Y-m-d')
,您可以使用:
<input type="text" class="form-control" id="dob" name="dob" value="<?php echo $this->swimmers->dob;?>"data-date-format="yy-mm-dd"><span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></跨度>
I have have a div with a user's date of birth pre-populated with php:
<div id="datepicker" class="input-group date">
<label for="dob">Date of Birth</label> <input type="text" class="form-control" id="dob" name="dob" value="<?php $date = new DateTime($this->swimmers->dob); echo $date->format('d/m/Y');?>"><span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
</div>
The javascript:
<script>
$('.container .input-group.date').datepicker({
startDate: "01/01/1900",
endDate: "01/01/2100",
format: "dd/mm/yyyy",
autoclose: true,
todayHighlight: true
});
</script>
Bootstrap is setup and working correctly however, when the "dob" input gets and loses focus without making a date selection it clears the value that was pre-populated.
This however doesn't happen if a date has been selected via the datepicker and then the input gets and loses focus.
How can the pre-populated value be kept in the field if someone clicks in it?
Edit: The first time you make a date selection, it clears the pre-populated value but doesn't insert the selected date until you make a date selection a second time.
Update: Working code updated!
解决方案Can't tell for sure without more of an example but the problem is probably that the $this->swimmers->dob
string you are giving to the input is not recognised as a date format by bootstrap-datepicker. You can define the date format it uses by adding the data-date-format
attribute to your input.
For example if you were using a MySQL formatted date or PHP's DateTime object with $date->format('Y-m-d')
you could use:
<div id="datepicker" class="input-group date">
<input type="text" class="form-control" id="dob" name="dob" value="<?php echo $this->swimmers->dob;?>" data-date-format="yy-mm-dd"><span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
</div>
相关文章