清除启动日期选取器值

Clear Bootstrap DatePicker Value

本文关键字:选取 日期 启动 清除      更新时间:2023-09-26

我在应用程序中使用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?
  });
});

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

如果#birthday包含日期选择器,执行此操作,它就会工作:

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

您需要对$('#birthday').data("DateTimePicker")对象调用clear。函数调用如图所示。

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

$('#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);
  });

似乎可以使用以下代码:

$('#clearButton').on('click', function() {
    alert('Clear the value in the "birthday" field...');
    $('#birthdayDate').val('');
    // what now?
})

这没问题$('#birthday').data("DateTimePicker").clear();

你可以看到这个http://eonasdan.github.io/bootstrap-datetimepicker/Functions/http://eonasdan.github.io/bootstrap-datetimepicker/Functions/#clear

注意:所有函数都可以通过数据属性访问,例如$('#datetimepicker').data("datetimepicker").FUNCTION()

步骤1:添加导入所需的引用:

import { bla-bla-bla, NgbInputDatepicker } from '@ng-bootstrap/ng-bootstrap';

步骤2:将其引用为ViewChild:

@ViewChild('lastStartMinDatepicker') lastStartMinDatepicker: NgbInputDatepicker;

考虑到你在标记中有这样的东西:

<input
   #lastStartMinDatepicker="ngbDatepicker"
   #thisElement="ngModel"
   ngbDatepicker
   (click)="lastStartMinDatepicker.toggle()"
   class="form-control"
   [class.is-invalid]="thisElement.invalid && thisElement.touched"
   [(ngModel)]="lastStartMinPicker"
   [ngModelOptions]="{ standalone: true }"
   placeholder="Date From"
   readonly
/>

步骤3:从中删除值:

this.lastStartMinDatepicker.writeValue(null);

步骤4:享受:)