2

I have a question based on data-binding with knockout and jquery datepicker from jQuery UI datepicker change event not caught by KnockoutJS

This works fine and well as long as the dateformat is dd-mm-yy. As soon as I change my dateform at to MM-yy the data binding is no longer updated. The date is instead set to today's date, regardless of what I choose in the listbox. Any tips on how I can make this work? I have multiple controls on multiple levels, so I would much prefer not to use this solution: Knockout with Jquery UI datepicker, MM/YY only

Thanks in advance.

Javascript:

ko.bindingHandlers.datepicker = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        $(element).datepicker({
            dateFormat: "dd-mm-yy",
            //dateFormat: "MM-yy",
            changeYear: true,
            changeMonth: true
        });

        //handle the field changing
        ko.utils.registerEventHandler(element, "change", function () {
            var observable = valueAccessor();
            observable($(element).datepicker("getDate"));
        });

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).datepicker("destroy");
        });

    },
    update: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
            current = $(element).datepicker("getDate");

        if (value - current !== 0) {
            $(element).datepicker("setDate", value);
        }
    }
};

html:

 <td><input class="dateField" data-bind="datepicker: plannedStartDate" /></td>

ViewModel:

...
self.plannedStartDate = ko.observable();
...
Community
  • 1
  • 1
user1384085
  • 55
  • 2
  • 9

1 Answers1

0

This seems like it's a bug with jquery datepicker. Whenever that format is used getDate doesn't return the correct value.

I have a partial solution that may work for you that recreates the solution you specified in your link.

http://jsfiddle.net/madcapnmckay/tKxAT/

It uses datejs to parse the datetext coming back from the datepicker. Not great since the day info is lost but it depends whether you want that. If not I suggest you may have to find another datepicker or change your format to include a date.

Hope this helps.

madcapnmckay
  • 15,782
  • 6
  • 61
  • 78