JSFiddle - React, Tailwind, and code Playground

by vyshniakov

HTML

<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.0.js"></script>
<div>
  <form>
    <p>You have asked for <span data-bind='text: gifts().length'>&nbsp;</span> gift(s)</p>
    <input
    id='giftname' type='text' data-bind='value: giftName' />
    <button data-bind='click: createGift'>Add Gift</button>
    <table>
      <thead>
        <tr>
          <th>Gift name</th>
          <th>Pack</th>
          <th>Price</th>
          <th />
        </tr>
      </thead>
      <tbody data-bind='foreach: gifts'>
        <tr>
          <td>
            <input data-bind='value: name' readonly='readonly' />
          </td>
          <td>
            <select data-bind="options: packs,
                                        optionsText: 'pack',
                                        optionsValue: 'packprice',
                                        value: price" />
          </td>
          <td>
            <input data-bind="value: price() || 'unknown'" readonly="readonly" />
          </td>
          <td><a href='#' data-bind='click: $root.removeGift'>Delete</a>

          </td>
        </tr>
      </tbody>
    </table>
    <button data-bind='enable: gifts().length > 0' type='submit'>Submit</button>
  </form>
</div>

JavaScript

function GiftModel(name, packs) {
  var self = this;

  self.name = ko.observable(name, packs);
  self.price = ko.observable();
  self.packs = ko.observable(packs);
}

var ViewModel = function (gifts) {
  var self = this;

  self.gifts = ko.observableArray(gifts);
  self.giftName = ko.observable();

  self.removeGift = function (gift) {
    self.gifts.remove(gift);
  };

  self.createGift = function () {
    // Get packs from the server.
    var packs = [{
      pack: 'Each',
      packprice: '2'
    }, {
      pack: 'Dozen',
      packprice: '12'
    }];
    self.gifts.push(new GiftModel(self.giftName(), packs));
  };
};

var viewModel = new ViewModel([]);
ko.applyBindings(viewModel);