mat mat - 1 year ago 282
jQuery Question

jQuery UI datepicker with Knockout.js

I am playing with knockout.js to add and remove fields in a form. So far it works okay, however i need a datepicker option, so i used jQuery's UI datepicker. This works, but only on the very first datepicker, not anywhere else. So whenever i click 'Add' i get new fields, but no datepicker.

I googled and seached StackExchange, but didn't find a solution on copying fields.


<table data-bind='visible: beschikkingen().length > 0'>
<th />
<tbody data-bind='foreach: beschikkingen'>
<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>


var beschikkingModel = function(beschikkingen) {
var self = this;
self.beschikkingen = ko.observableArray(beschikkingen);

self.addbeschikking = function() {
beschikkingsdatum: "",
beschikkingsnummer: ""

self.removebeschikking = function(beschikking) {
}; = 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: ""

// Activate jQuery Validation
$("form").validate({ submitHandler: });


dateFormat: 'dd-mm-yy',
constrainInput: false

gbs gbs
Answer Source

Using a custom binding handler can solve your problem:

ko.bindingHandlers.datepicker = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var options = allBindingsAccessor().datepickerOptions || {};

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

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {

And in HTML:

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

Here is the working fiddle:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download