var viewModel = {}; viewModel.Product = ko.observable(null); viewModel.Products = [ "Satin Pyjamas", "Jeans", "Leather Wallet" ]; viewModel.GiftWrap = ko.observable("No"); viewModel.Greating = ko.observable(""); viewModel.Delivery = ko.observable("Kharkov"); viewModel.Address = ko.observable(""); viewModel.Carrier = ko.observable(null); viewModel.Carriers = ["Autolux", "International", "Express"]; viewModel.Summary = ko.dependentObservable( function(){ var summary = ""; summary += this.Product(); summary += (this.GiftWrap() == 'Yes') ? " in gift wrap" : " in simple wrap"; summary += (this.GiftWrap() == 'Yes' && this.Greating() != '') ? (" with greating '" + this.Greating() + "'") : ""; summary += "<br />"; summary += "Delivery address: " + this.Address(); summary += (this.Delivery() == 'Ukraine') ? " with " + this.Carrier() + " carrier" : ""; summary += "<br />"; return summary; }, viewModel); viewModel.Total = ko.dependentObservable( function() { var total = 0; total += (this.GiftWrap() == 'Yes') ? 20 : 5; if (this.Delivery() == 'Kharkov'){ total += 30; } else { if (this.Carrier() == 'Autolux'){ total += 20; } if (this.Carrier() == 'International'){ total += 10; } if (this.Carrier() == 'Express'){ total += 35; } } return total; }, viewModel); ko.applyBindings(viewModel, document.getElementById("koSample"));
<div id="koSample"> <div> <label>Product</label> <select data-bind="options: Products, value: Product"> </select> </div> <div> <label>Gift Wrap</label> <input type="radio" name="wrap" value="Yes" data-bind="checked: GiftWrap" /> Yes <input type="radio" name="wrap" value="No" data-bind="checked: GiftWrap" /> No </div> <div data-bind="visible: GiftWrap() == 'Yes'"> <label>Greating</label> <input type="text" data-bind="value: Greating, valueUpdate: 'keyup'" /> </div> <div> <label>Delivery</label> <input type="radio" name="delivery" value="Kharkov" data-bind="checked: Delivery" /> Kharkov <input type="radio" name="delivery" value="Ukraine" data-bind="checked: Delivery" /> Ukraine </div> <div> <label>Address</label> <input type="text" data-bind="value: Address" /> </div> <div data-bind="visible: Delivery() == 'Ukraine'"> <label>Carrier</label> <select data-bind="options: Carriers, value: Carrier"> </select> </div> <div> Summary <p> <span data-bind="html: Summary"></span><br /> <div id="total">Total: $<span data-bind="text: Total"></span></div> </p> </div> </div>