NoviceDeveloper
NoviceDeveloper

Reputation: 1290

knockoutjs MVC 4 computed values

I have the following viewModel

        var viewModel = new myViewModel([{
            Name: "Name",
            price: 32,
            tax: 22,
        }, {
            Name: "Name",
            price: 32,
            tax: 22,
        }]);

I have a data-bind to

       <tbody data-bind='foreach: personInfo'>

and input:

        <td>
        <input class='required' data-bind='value: Name'/>
        </td>
        <td>
        <input class='required' data-bind='value: Price'/>
        </td>
        <td>
        <input class='required' data-bind='value: Tax'/>
        </td>

and I want to get the computed value for price and then for tax however I am not successful. :(

        self.totalSurcharge = ko.computed(function () {
        var total = 0;
        for (var i = 0; self.PersonInfo().length; i++)
        total += self.PersonInfo[i].price;
        return total;
        });

any idea?

UPDATE:

something like this: http://jsfiddle.net/hamsaya/9XNDH/1/

Thanks

Upvotes: 2

Views: 541

Answers (3)

NaveenKumar1410
NaveenKumar1410

Reputation: 1613

I have tested the below code which is working fine,

Modify your html as below:

 <tr>
     <td> Total of price here</td>
     <td data-bind="text:totalPrice"></td>
 </tr> 

Add below Computed Observable in your script to calculate total price:

self.totalPrice = ko.computed({
    read: function() {
    var totalAmount = null;
    for(var i=0 , j=self.gifts().length ; i < j ; i++ )
    {
         totalAmount =Number(totalAmount)+ Number(self.gifts()[i].price);
    }
    if(totalAmount == 0){
        totalAmount = '0.00'
        }
    return totalAmount;
}
});

Upvotes: 1

NoviceDeveloper
NoviceDeveloper

Reputation: 1290

interesting enough they have to update the site:

here is the answer.

    self.totalSurcharge = ko.computed(function () {
    var total = 0;
    for (var i = 0; i < gifts.length; i++)
    total =total+ gifts[i].price;
    return total;
    });  

Upvotes: 2

blaster
blaster

Reputation: 8937

According to the documentation, you need to use parantheses to access the KO-wrapped observable array before using an indexer to access data from it:

http://knockoutjs.com/documentation/observableArrays.html

Try replacing

self.PersonInfo[i].price

with

self.PersonInfo()[i].price

Upvotes: 1

Related Questions