JSFiddle - React, Tailwind, and code Playground

by kougiland

HTML

<div data-bind="foreach: ages">
  <input type="number" data-bind="value: age" />
  <span data-bind="text: age"></span>
    <br/>
</div>

JavaScript

ko.extenders.defaultIfBlank = function(target, defaultValue) {
  var result = ko.computed({
    read: target,  //always return the original observables value
    write: function(newValue) {
        if (newValue == "") {
          target(defaultValue);
        } else {
           target(newValue);
        }
    }
  });

  //initialize with current value to make sure it is not blank
  result(target());

  //return the new computed observable
  return result;
};

var model = function() {
  this.ages = ko.observableArray([
      {age: ko.observable(13).extend({defaultIfBlank: "0"})},
      {age: ko.observable(18).extend({defaultIfBlank: "0"})},
      {age: ko.observable(16).extend({defaultIfBlank: "0"})},
      {age: ko.observable(13).extend({defaultIfBlank: "0"})}
  ]);
};

ko.applyBindings(new model());