I am using Knockout JS library to bind the HTML5 input controls in my Web application which is intended to run on iPad (iOS5, Safari 5.1). The binding works fine for the input types like text and select but not for date. After selecting a date value through the datepicker the value is not getting bound to the viewModel property (in effect not getting saved).
This is how my HTML looks.
<input id="dob" name="dob" type="date" data-bind="value: dob" />
I tried to work around with a custom binding where I initialized a change event handler.
ko.bindingHandlers.datePicker = {
init: function (element, valueAccessor) {
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor();
observable($(element).val());
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).val(value);
}
};
Changing the HTML code to -
<input id="dob" name="dob" type="date" data-bind="datePicker: dob" />
Strangely, even that event is not firing. Please note that in both of the scenarios the binding happens perfectly in Windows XP on Opera and Safari browsers.
Ultimately, I got the solution to my problem by using the 'blur' event instead of 'change' in the custom binding. Now the event handler is being called and I am manually setting the value from the date control.
Now my question is, is it something that I am not doing correctly and if not then why doesn't the change event of the HTML5 date control not fire, whether by default or through custom binding? I want the date control to work as it is supposed to.
You are not doing anything wrong from a Knockout perspective. Those events really just are not fired (without Knockout even in the picture) from what I can tell by testing and by researching it a bit.
You can avoid a custom binding by doing:
<input type="date" data-bind="value: myDate, valueUpdate: 'blur'" />
I had similar issue, but in my case, even the blur event is actually not fired. So I used input event with valueUpdate property, and resolved the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With