Search code examples
jqueryknockout.jsknockout-mapping-plugin

Knockout total value for each row


I think I've tried everything on this one, but I cannot figure this out. I'm simply trying to update the total price for each row in a table when the user increases the quantity. So far I've tried

  • math in the HTML: data-bind="text: parseFloat((total * quantity), 10)"
  • using ko.computed() (which "works" but returns the same value for each row's total)
  • subscribing to an event
  • looping through each observableArray's item with ko.utils.arrayForEach and jQuery $.each()
  • adding a ko.computed property with a create() function as part of a mapping option, but I didn't really understand that one.

Here's a fiddle. If anyone has any suggestions as to how I can accomplish this seemingly simple task I'd appreciate it.

Most of the failed attempts are in the comments on that fiddle. The closest I've come was the ko.computed but I could only get it to return one value - the value for the last row in the table. Thanks


Solution

  • Depends what you want to achieve. For simple display purpose a function will do:

    viewModel.calcTotal = function ( row ) {
        return parseFloat(( row.total() * row.quantity() ), 10);
    };
    

    There is special variable in for loop $data that will pass your row data:

    <td><span data-bind="text: $root.calcTotal($data)"></span></td>
    

    Also, your first point with math in HTML will work if you add parentheses. Simple form of binding observables won't work in expressions.

    data-bind="text: parseFloat(( total() * quantity() ), 10)"