Bootstrap 3 DatePicker - How to reset selected date without resetting the picker configuration?

限于喜欢 提交于 2020-01-23 06:20:07

问题


I'm trying to reset the selected date on button click, but so far I'm only able to clear the input element, without the actual date on the picker. The following code resets everything, including the configuration and the date, so its obviously not what I need.

$('#datepicker').datepicker('update',''); //resets everything

To elaborate: The user can only select a date 7 days from the current day. There's also a button that enables the user to clear the selected date from the picker, and select a new one. Right now, the clearing function can only clear the input element from the picker (but not the actual date in the picker element), or to clear the selection WITH the picker configuration (ex. the startDate: "+7d". I want to clear only the selected date, without resetting everything.

jsfiddle

This is what I came up with so far:
HTML:

<div id="myDatepicker" class="input-group date">
   <input type="text" class="form-control" id="datepick">
   <span class="input-group-addon">
   <i class="fa fa-calendar"></i>
   </span>
   <a href="#" id="duration_tag"></a>
</div>
<button type="button" id="clear">clear</button>

jQuery:

$(document).ready(function() {

$("#clear").click(function(){
    $('#datepick').val(" ").datepicker({startDate: "+7d"});                  
});

$('#myDatepicker').datepicker({
                    startDate: "+7d",
                });

$('#myDatepicker').on('changeDate', function(e){
     $(this).datepicker('hide');
});

});

回答1:


You need to get the current datePicker instance and call setDate(null) on it. you can do it like this:

$("#clear").click(function(){
  $('#myDatepicker').data('datepicker').setDate(null);
});

updated fiddle: http://jsfiddle.net/4L6fhjLf/2/




回答2:


$('#myDatepicker').data('DateTimePicker').date(null);



回答3:


For some reason neither of the above examples worked for me, but the following did:

$('#myDatepicker').data('DateTimePicker').clear(); // clears input value 

which is effectively the same as Dirk Vermeer's answer which did not work for what I was looking for.

I needed to also change the viewMode to start the picker process over, in my case this was decades you may need a different viewMode option:

$('#myDatepicker').data('DateTimePicker').clear().viewMode('decades')


来源:https://stackoverflow.com/questions/31003648/bootstrap-3-datepicker-how-to-reset-selected-date-without-resetting-the-picker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!