Regards, I have a requirement in the use of knockoutJs with bootstrap datepicker. You need to have date range.
Requirements: I have two datepickers. - The first datepicker gets the value for the field since. - The second datepicker gets the value for the field up. - You need to get the difference in days between the two dates.
Flow
When the page loads, the datepicker with the field from start to the current date.
The second datepicker (to field) starts empty.
Each time, we selected a date (from field), the value of the second field (to field) is reset.
When selecting a date (from field), the available dates (to field) are those between (from field) forward.
Start the flow from step 3.
Calculation Date
- Every time there dates in their respective fields, calculate the difference in days.
The fiddle: example fiddle
function viewModelCustom() {
var self = this;
var today = new Date();
var todayFormat = moment(today).format('DD/MM/YYYY');
self.StartDate = ko.observable(todayFormat);
self.EndDate = ko.observable(todayFormat);
self.diffDays = ko.computed(function() {
var result;
var start = moment(self.StartDate(), 'DD/MM/YYYY');
var end = moment(self.EndDate(), 'DD/MM/YYYY');
result = Math.abs(start.diff(end, "days")) + 1;
return result;
});
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {
format: 'dd/mm/yyyy'
};
$(element).datepicker(options);
//when a user changes the date, update the view model
ko.utils.registerEventHandler(element, "changeDate", function(event) {
var value = valueAccessor();
if (ko.isObservable(value)) {
value(event.date);
}
});
},
update: function(element, valueAccessor) {
var widget = $(element).data("datepicker");
//when the view model is updated, update the widget
if (widget) {
widget.date = ko.utils.unwrapObservable(valueAccessor());
widget.setValue();
}
}
};
}
ko.applyBindings(new viewModelCustom());