morleyc
morleyc

Reputation: 2431

Dynamically create checkboxes and calculate total depending on checkboxes ticked

I get addons data from the server, and need to dynamically create the viewmodel with a number of checkboxes, and then total these checkboxes according to the checkbox selected and its price.

My viewModel is below:

var addonsData = [
    { sku: 201, name: "addon A", price: 1 }
    { sku: 201, name: "addon B", price: 2 }
    { sku: 201, name: "addon C", price: 10 }
];

function viewModel(addonsData) {
    for (var i = 0; i < addonsData.length; i++) {
      // addonsData[i] somehow add this to the viewmodel dynamically?
    }

    this.addons = addonsData;
    this.total = ko.computed(function(){
        var x = 0;
        return x;
    });
}

ko.applyBindings(new viewModel(addonsData));

Would greatly appreciate guidance on the above viewmodel and also the HTML view.

Upvotes: 2

Views: 261

Answers (1)

Damien
Damien

Reputation: 8987

The simpliest way is to use ko.mapping.fromJS

Take a look at this fiddle

var addonsData = [{
    sku: 201,
    name: "addon A",
    price: 1
}, {
    sku: 201,
    name: "addon B",
    price: 2
}, {
    sku: 201,
    name: "addon C",
    price: 10
}];

function viewModel(ad) {
    var self = this;

    var mapping = {
        create: function (item) {
            item.data.selected = ko.observable();
            return item.data;
        }
    };
    this.addons = ko.mapping.fromJS(ad, mapping);



    this.selectedItems = ko.computed(function () {
        return ko.utils.arrayFilter(self.addons(), function (item) {
            return item.selected();
        });
    });
    this.total = ko.computed(function () {
        return self.selectedItems().length;
    });

    this.totalPrice = ko.computed(function () {
        var t = 0;
        ko.utils.arrayForEach(self.addons(), function (item) {
            if(item.selected())
               t += item.price;
        });
        return t;
    });

}

ko.applyBindings(new viewModel(addonsData));

See fiddle

I hope it helps.

Upvotes: 2

Related Questions