I'm using bootstrap datepicker and binding the selected date with knockoutjs in an asp.net mvc application
Knockout Binding:
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {
useCurrent: false,
format: 'mm/dd/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();
}
}
};
var model = {
StartDate: ko.observable(),
EndDate: ko.observable()
};
ko.applyBindings(model, $("#target")[0]);
Right now, after completing the form, the form is submitted to the server using ajax post.
On return, I want to clear the selected start and end dates input fields.
I have tried this:
self.StartDate(null);
self.EndDate(null);
this clears the properties, but the input still retains the selected dates. Is there a way to clear not just the properties, but also the input values?
Also, in the knockout custom binding init function, is there a way to link both date inputs to make it a range, like the demo here? In the demo, when Range radio button is selected, but fields work together as a range.
var value = ko.utils.unwrapObservable(valueAccessor());
then last line in your update, you could do$(element).val(value);
to change the input value which datepicker component is giving (observable is changed normally, so no worries here) - kasperoo