简体   繁体   English

敲除js以从引导日期选择器中的选定日期禁用过去的日期

[英]Knockout js to disable past date from the selected date in bootstrap datepicker

Html code to bind the knockout model HTML代码绑定敲除模型

     <tbody data-bind="foreach: responseUserSetUpData().userListViewModel">
                        <tr>
                            <td><input type="text" class="datepicker form-control"  data-bind="datePicker: ko.observable(new Date(FormatStartDate)) , textInput : FormatStartDate , attr: {id: UserId}, datePickerOptions: {startDate: new Date()}"></td>
                            <td><input type="text" class="datepicker form-control" data-bind="datePicker: ko.observable(new Date(FormatEndDate)), textInput: FormatEndDate , attr :{id: UserId}, datePickerOptions: {startDate: new Date(FormatStartDate)}" ></td>
                        </tr>
                        </tbody>

Knockout Js custome Binding for date picker 敲除日期选择器的Js自定义绑定

    ko.bindingHandlers.datePicker = {
            init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
                var unwrap = ko.utils.unwrapObservable;
                var dataSource = valueAccessor();
                var binding = allBindingsAccessor();
                var options = {
                    keyboardNavigation: true,
                    todayHighlight: true,
                    autoclose: true,
                    daysOfWeekDisabled: [0, 6],
                    format: 'mm/dd/yyyy',
                    startDate: userManagementVM.StartMeetingDate()
                };
                if (binding.datePickerOptions) {
                    options = $.extend(options, binding.datePickerOptions);
                }
                $(element).datepicker(options);
                $(element).datepicker('update', dataSource());
                $(element).on("changeDate", function (ev) {
                    var observable = valueAccessor();
                    if ($(element).is(':focus')) {
                        $(element).one('blur', function (ev) {
                            var dateVal = $(element).datepicker("getDate");
                            observable(dateVal);
                        });
                    }
                    else {
                        observable(ev.date);
                    }
                });
                //handle removing an element from the dom
                ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                    $(element).datepicker('remove');
                });
            },
            update: function (element, valueAccessor) {
                var value = ko.utils.unwrapObservable(valueAccessor());
                $(element).datepicker('update', value);
            }
        };

Now, I want to disable all the past date in calender from the selected start date. 现在,我想从所选开始日期开始禁用日历中的所有过去日期。 It should disable all the past date from the selected date. 它应该禁用所选日期之后的所有过去日期。

Here is the two property of the view model 这是视图模型的两个属性

StartMeetingDate: ko.observable(new Date()),
    EndMeetingDate: ko.observable(),

How can I disable all the past date in calender using knockout custome binding. 如何使用敲除自定义绑定禁用日历中的所有过去日期。

This is updated answer that takes into account that low limit on endDateLowLimit should be set not only on startup but also should be updated dynamically each time startMeetingDate has changed 此更新的答案考虑到endDateLowLimit应该在启动时设置endDateLowLimit下限,而且每次startMeetingDate更改时都应该动态更新startMeetingDate

As I've said in a comment I don't believe that there is 'pure knockout' way to implement this dynamic behavior. 正如我在评论中所说,我不相信有“纯粹的淘汰赛”方式可以实现这种动态行为。

Though you can apply custom event fired each time startMeetingDate is changed and customize the datePicker binding to react on the event. 尽管您可以应用每次更改startMeetingDate触发的自定义事件,并自定义datePicker绑定以对该事件作出反应。

You View Model then may look like this: 您的View Model可能看起来像这样:

function ViewModel(){
    var self   = this;
    //    ..... 
    self.startDateLowLimit = ko.observable(new Date());
    self.startDateHihgLimit = ko.pureComputed(function(){
        return new Date(self.startDateLowLimit().getTime() + 30 * 86400000);    //  roughly 30 days from self.startMeetingDate()
    });

    self.startMeetingDate = ko.observable(self.startDateLowLimit());

    self.startMeetingDate.subscribe(function(newStartDate) { $('#endDate').trigger('DATE-FROM-CHANGED', [newStartDate])});    //    this is where custom event is fired


    self.endDateLowLimit = ko.pureComputed(function(){
        return self.startMeetingDate();
    });
    self.endMeetingDate = ko.observable(null);
    //    ..... 
}

The markup maybe like this: 标记可能像这样:

<label>Start meeting date</label>
<input type="text" class="datepicker form-control"  id="startDate"  data-bind="datePicker: startMeetingDate, datePickerOptions: {startDate: startDateLowLimit(), endDate: startDateHihgLimit()}" >
<label>End meeting date</label>
<input type="text" class="datepicker form-control"  id="endDate"  data-bind="datePicker: endMeetingDate, datePickerOptions: {startDate: endDateLowLimit()}" >

Note that having id="endDate" attribute in second input is essential because self.startMeetingDate.subscribe handler uses this id to target the event. 请注意,在第二个输入中具有id="endDate"属性是必不可少的,因为self.startMeetingDate.subscribe处理程序使用此ID来定位事件。

Also note using datePickerOptions along with datePicker in the data-bind . 还要注意使用datePickerOptions沿datePickerdata-bind We need it to set initial options of the datepicker . 我们需要它来设置datepicker初始选项。

And now to customizing the datePicker binding. 现在自定义datePicker绑定。 Add this code that creates event handler into the binding's init method. 将此创建事件处理程序的代码添加到绑定的init方法中。

Just before this comment //handle removing an element from the dom would be a nice place. 在此注释之前//handle removing an element from the dom将是一个不错的地方。

$(element).on('DATE-FROM-CHANGED', function (ev, newStartDate) {
    const isDateValid = function(date) {
        //    this is a utility function that checks either parameter is a valid date
        return date.getTime && date.getTime() === date.getTime();    //    invalid date object returns NaN for getTime() and NaN is the only object not strictly equal to itself
    }

    var currentDate = $(ev.target).datepicker('getDate');
    if (isDateValid(newStartDate) && isDateValid(currentDate) && currentDate < newStartDate) {
        //    we should clean the current date if it is less then the new start date
        $(ev.target).datepicker('setDate', null);
    }
    $(ev.target).datepicker('setStartDate', newStartDate);    //    this is exactly where we set new start date for the datepicker
});

There still may be a full range of corner cases you'll have to cope with though I believe this answer helps you to get the general idea. 尽管我相信这个答案可以帮助您获得一般性的想法,但仍然可能有各种各样的情况需要您解决。

You may also find useful this documentation https://bootstrap-datepicker.readthedocs.io/en/latest/methods.html in case you've missed it. 如果您错过了本文档,您可能还会发现它很有用https://bootstrap-datepicker.readthedocs.io/en/latest/methods.html

Below is a link to more elaborative (yet more hackerish) example that involves a range of date picker pairs placed on separate table rows. 下面是一个链接,链接到更详尽的示例(但更加骇人听闻),该示例涉及放置在单独的表行上的一系列日期选择器对。 Note that knockout's subscribe is not involved in message passing in the example. 请注意,示例中的消息传递不涉及敲除的subscribe

https://jsfiddle.net/rLh2r9pw/19/ https://jsfiddle.net/rLh2r9pw/19/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM