Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout JS: Change event not firing for HTML5 date on iPad

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.

like image 371
Viplove Sharma Avatar asked Dec 28 '11 09:12

Viplove Sharma


2 Answers

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'" />

like image 141
RP Niemeyer Avatar answered Sep 24 '22 19:09

RP Niemeyer


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.

like image 32
ailerifren Avatar answered Sep 22 '22 19:09

ailerifren