Reputation: 3562
I have a to and from date range datepicker (jquery) that I am trying to bind the selected values to to knockout observables. The date pickers to and from limit the date range a user can select and defaults to the past 30 days once the user selects the "from" date.
I have bound two span element to test the bindings to the value of the observables however whenever I select a date the datepicker sets the fields appropriately but the observables are never triggered/updated.
html
From
<input type="text" id="StartDate" data-bind="value: myStartDate()" />to
<input type="text" id="EndDate" data-bind="value: myEndDate()"/>
<hr/>
<p>start day<span data-bind="text: myStartDate()" />
</p>
<p>end day<span data-bind="text: myEndDate()" />
</p>
js (and ko combined)
var myViewModel = function () {
var self = this;
self.myStartDate = ko.observable();
self.myEndDate = ko.observable();
};
ko.applyBindings(new myViewModel());
//calendar controls
//setup min and max date ranges
var d = new Date();
d.setDate(d.getDate());
//default range
var defRange = 30;
// total range 1yr +/-
var e = new Date();
var xDate = 365;
e.setDate(d.getDate() - xDate);
$('#StartDate').datepicker({
maxDate: d,
beforeShow: function () {
$('.ui-datepicker').css('font-size', 10);
},
onSelect: function (date) {
var dp2 = $('#EndDate');
var startDate = $(this).datepicker('getDate');
var minDate = $(this).datepicker('getDate');
startDate.setDate(startDate.getDate() + xDate);
//defaults to past 30 days
dp2.datepicker('setDate', -defRange);
minDate.setDate(minDate.getDate() - xDate);
//set max date for start and end range
dp2.datepicker('option', 'maxDate', startDate);
dp2.datepicker('option', 'minDate', minDate);
$(this).datepicker('option', 'minDate', minDate);
}
});
$('#EndDate').datepicker({
maxDate: d,
minDate: e,
beforeShow: function () {
$('.ui-datepicker').css('font-size', 10);
}
});
$('#StartDate').focus(function () {
$('#StartDate').datepicker('show');
});
$('#EndDate').focus(function () {
$('#EndDate').datepicker('show');
});
Where I am stuck is in understanding what I need to do get the values set once a date is selected in the datepicker and populated to the input fields pushed across to the observables.
Thanks for any hints or suggestions,
Upvotes: 1
Views: 7666
Reputation: 29703
1) First of all you should use
data-bind="value: myStartDate"
instead of
data-bind="value: myStartDate()"
With this changes, second datepicker works as expected.
2) First datepicker doesn't work, because you set value manually (.datepicker('setDate', ..);
)
You should trigger change
event on inputs to update observables.
///
startDate.setDate(startDate.getDate() + xDate);
$(this).change()
///
dp2.datepicker('setDate', -defRange);
dp2.change();
///
Upvotes: 3