0

I have an input field that asks user to pick a date and if the date is less than 30 days form today it will display some other contents. I am using jQueryUI datapicker and knockout.js for data binding and here is what I have so far JSFiddle but it's not working. What am I missing?

$(document).ready(function() {
  $("#datepicker").datepicker();
});

$(document).ready(function() {

  var viewModel = function() {
    var self = this;
    self.request_due_date = ko.observable();
    self.request_due_date_rush = ko.observable(false);
    self.request_due_date_rush_reason = ko.observable();

    self.request_due_date.subscribe(function(dd) {
      var cur = new Date(),
        rush_date = cur.setDate(cur.getDate() + 30);
      if (dd < rush_date) {
        self.request_due_date_rush(true);
      }
    });
  };
  ko.applyBindings(new viewModel());
});
<div>Due Date:
  <input id="datepicker" data-bind="text: request_due_date" type="text" />
</div>
<div data-bind="visible: request_due_date_rush">Reason For Rush:
  <input data-bind="text: request_due_date_rush_reason" />
</div>
Saeed Abbaspour
  • 329
  • 4
  • 16

3 Answers3

0

You need to bind value, not text.

<input id="datepicker" data-bind="value: request_due_date" type="text" />

Also the value dd is a string and must be parsed to date, for example using moment.js

var days = moment().diff(moment(dd, "MM/DD/YYYY"), "days");

See updated fiddle

Max Brodin
  • 3,903
  • 1
  • 14
  • 23
0

it's because when you create the datepicker object, the underlying input element gets moved around in the DOM, breaking the binding. Consider writing your own binding handler, like seen here: jQuery UI datepicker change event not caught by KnockoutJS

Community
  • 1
  • 1
dfperry
  • 2,258
  • 1
  • 14
  • 22
0

Thanks to @MaxBrodin for the insight (to bind value, not text) and this post I found the following solution to be working. Here is also the updated Fiddle

$(document).ready(function() {
  $("#datepicker").datepicker();
});

$(document).ready(function() {

  var viewModel = function() {
    var self = this;
    self.request_due_date = ko.observable();
    self.request_due_date_rush = ko.observable(false);
    self.request_due_date_rush_reason = ko.observable();

    self.request_due_date.subscribe(function(dd) {
      var date1 = new Date(dd);
      var date2 = new Date();
      var timeDiff = Math.abs(date2.getTime() - date1.getTime());
      var days = Math.ceil(timeDiff / (1000 * 3600 * 24));

      self.request_due_date_rush(days < 30);
    });
  };
  ko.applyBindings(new viewModel());
});
<div>Due Date:
  <input id="datepicker" data-bind="value: request_due_date" type="text" />
</div>
<div data-bind="visible: request_due_date_rush">Reason For Rush:
  <input data-bind="text: request_due_date_rush_reason" />
</div>
Community
  • 1
  • 1
Saeed Abbaspour
  • 329
  • 4
  • 16