0

I am trying to bind a datepicker to my template property in knockout as per this example: http://jsfiddle.net/H8xWY/130/

From fiddler it looks pretty straightforward but the issue is that when I focus on date textbox the datepicker doesn't come up at all. There is no console errors neither. Not sure why nothing is happening and what I've missed?

My model:

var MyViewModel = function(model) {
    var self = this;

    self.date = ko.observable(new Date());
}

My template:

<div id="my-form">
            <input data-bind="datepicker: date, datepickerOptions: { minDate: new Date() }" />

</div>
<script src="models/my-model.js" type="text/javascript"></script>
<script type="text/javascript">
    var target = document.getElementById("my-form");
    var data = @Html.Raw(Json.Encode(Model));
    var myViewModel = new MyViewModel(data);
    ko.applyBindings(myViewModel, target);
</script>
nickornotto
  • 1,946
  • 4
  • 36
  • 68

1 Answers1

0

Add knockout extension of date picker

ko.bindingHandlers.datepicker = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            //initialize datepicker with some optional options
            var options = allBindingsAccessor().datepickerOptions || {};
            $(element).datepicker(options);

            //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());

            //handle date data coming via json from Microsoft
            if (String(value).indexOf('/Date(') == 0) {
                value = new Date(parseInt(value.replace(/\/Date\((.*?)\)\//gi, "$1")));
            }

            current = $(element).datepicker("getDate");

            if (value - current !== 0) {
                $(element).datepicker("setDate", value);
            }
        }
    };
Shohel
  • 3,886
  • 4
  • 38
  • 75
  • It works without the extension but if I have a datepicker in a template and select a date on the second item - it updates the date in the first item. – nickornotto Jul 14 '17 at 14:46