two datepickers with knockout, one updates another

耗尽温柔 提交于 2019-12-23 17:53:28

问题


I got attached jQuery datepicker with knockout custom bindings handler, and I want to when updating first field to set minDate of second to day after (in case that other date was not set to later date).

<label>Check-in:</label>
<input type="date" id="checkIn" data-bind="datepicker: checkIn, datepickerOptions: {
    minDate: 0,
    dateFormat: 'dd/mm/yy',
    firstDay: 1
    }" />
<br/>
<br/>

<label>Check-out:</label>
<input type="date" id="checkOut" data-bind="datepicker: checkOut, datepickerOptions: {
    minDate: 0,
    dateFormat: 'dd/mm/yy',
    firstDay: 1
    }" />

I have setup fiddle for that

e.g. If for checkOut date is selected 28/11/2012 and you for checkIn choose 25/11/2012 there is no need to change checkOut date, only to set minDate of checkOut to 26/11/2012.

But if you choose 29/11/2012 for checkIn, then checkOut needs to update to 30/11/2012


回答1:


One way to do it is to subscribe to the first date observable property and use that to set the second:

self.checkIn.subscribe(function(newValue) {
    $("#checkOut").datepicker("option", "minDate", self.checkIn());
});

See here

Of course, this is not the most elegant solution, since it requires knowing which part of the view relates to the other property. A better solution might be to create another custom binding.

Something like this:

ko.bindingHandlers.minDate = {
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
        current = $(element).datepicker("option", "minDate", value);
    }        
}

Bound like this:

<input type="date" id="checkOut" data-bind="{datepicker: checkOut, datepickerOptions: {
minDate: 0,
dateFormat: 'dd/mm/yy',
firstDay: 1
},
minDate: checkIn}" />

See here.



来源:https://stackoverflow.com/questions/13496605/two-datepickers-with-knockout-one-updates-another

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