JQuery UI datepicker with Knockout.js

I play with knockout.js to add and remove fields in a form. While this works fine, however, I need the datepicker option, so I used the jQuery UI datepicker. This works, but only on the very first datepicker, and not anywhere else. Therefore, whenever I click Add, I get new fields, but no datepicker.

I googled and seached StackExchange , but did not find a solution for copying fields.

HTML

<table data-bind='visible: beschikkingen().length > 0'> <thead> <tr> <th>Beschikkingsdatum</th> <th>Beschikkingsnr</th> <th /> </tr> </thead> <tbody data-bind='foreach: beschikkingen'> <tr> <td><input name="beschikkingsdatum[]" type="text" class="beschikkingsdatum" value="" data-bind='value: beschikkingsdatum, uniqueName: true' /> </td> <td><input class='required number' data-bind='value: beschikkingsnummer, uniqueName: true' /></td> <td><a href='#' data-bind='click: $root.removebeschikking'>Delete</a></td> </tr> </tbody> </table> 

Knockout.js

 var beschikkingModel = function(beschikkingen) { var self = this; self.beschikkingen = ko.observableArray(beschikkingen); self.addbeschikking = function() { self.beschikkingen.push({ beschikkingsdatum: "", beschikkingsnummer: "" }); }; self.removebeschikking = function(beschikking) { self.beschikkingen.remove(beschikking); }; self.save = function(form) { alert("Could now transmit to server: " + ko.utils.stringifyJson(self.beschikkingen)); // To actually transmit to server as a regular form post, write this: ko.utils.postJson($("form")[0], self.beschikkingen); }; }; var viewModel = new beschikkingModel([ { beschikkingsdatum: "", beschikkingsnummer: "" } ]); ko.applyBindings(viewModel); // Activate jQuery Validation $("form").validate({ submitHandler: viewModel.save }); //]]> 

Datepicker

 $(window).load(function(){ $('.beschikkingsdatum').datepicker({ dateFormat: 'dd-mm-yy', constrainInput: false }); }); 
+4
source share
1 answer

Using a special binding handler may solve your problem:

 ko.bindingHandlers.datepicker = { init: function (element, valueAccessor, allBindingsAccessor) { 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"); }); } }; 

And in HTML:

 <input data-bind='datepicker: beschikkingsdatum' /> 

Here is a working fiddle: http://jsfiddle.net/QUxyy/

+9
source

All Articles