2

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

NoviceDeveloper
  • 1,270
  • 3
  • 15
  • 41
  • 1
    Can you post an example of where PersonInfo is declared, and also describe where you're attempting to define the totalSurcharge computed observable? – blaster Mar 04 '13 at 17:27
  • suppose this http://jsfiddle.net/hamsaya/9XNDH/1/ I want where it says total of price here. That is how I want to calculate it. – NoviceDeveloper Mar 04 '13 at 18:17

3 Answers3

2

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;
    });  
NoviceDeveloper
  • 1,270
  • 3
  • 15
  • 41
1

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
blaster
  • 8,876
  • 11
  • 48
  • 77
1

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;
}
});
NaveenKumar1410
  • 1,565
  • 14
  • 20