清除Bootstrap DatePicker值

Som*_*ser 3 javascript jquery datepicker

我在我的应用程序中使用Bootstrap DatePicker控件。我试图弄清楚如何清除该字段的值。问这个问题我有点傻。老实说,它看起来应该很简单。但是,我一直没有成功。我已经尝试过在本SO帖子中推荐的方法,但是没有运气。

目前,我有这个JSFiddle。我的问题代码如下所示:

$(function() {
  $('#birthday').datetimepicker({ showTodayButton: true });
  $('#getDateButton').on('click', function() {
    var selectedDate = $('#birthday').data('date');
    if (selectedDate) {
      selectedDate = selectedDate.format('MM-DD-YYYY');
    }
    $('#formattedDate').html(selectedDate);
  });

  $('#clearButton').on('click', function() {
    alert('Clear the value in the "birthday" field...');
    $('#birthday').data('clear');
    // what now?
  });
});
Run Code Online (Sandbox Code Playgroud)

就像控件中的功能不起作用一样。或者,文档不正确。如小提琴所示,我的“获取日期”功能也不起作用。这就是为什么我觉得有些不对劲。我错过了什么还是误会了?

Chi*_*tan 5

如果#birthday包含日期选择器,请执行此操作,它将起作用:

$('#clearButton').on('click', function() {
    alert('Clear the value in the "birthday" field...');
    $('#birthday').data("DateTimePicker").clear();
  });
Run Code Online (Sandbox Code Playgroud)

您需要在该对象上调用clear$('#birthday').data("DateTimePicker")这里说明函数调用。

要获取日期,请执行以下操作:

$('#getDateButton').on('click', function() {
    var selectedDate = $('#birthday').data('DateTimePicker').date();

    if (selectedDate) {
      selectedDate = selectedDate.format('MM-DD-YYYY');
      console.log("selected date "+ selectedDate);
    }
    $('#formattedDate').html(selectedDate);
  });
Run Code Online (Sandbox Code Playgroud)