Getting total row sum and adding and removing rows using knockoutjs
I'm new to knockouts. I am creating a simple table and trying to sum all the values in the "total" column. In addition, I also implement the Add Column and Remove Columns functionality using knockoutjs.
The problem is that both Add and Remove funcitonalities don't work. In addition, the "TotalSurcharge" value is not displayed in the user interface.
Here's my js:
// Class to represent a row in the table
function addMaterial() {
this.name = ko.observable("");
this.quantity = ko.observable("");
this.rate = ko.observable(0);
this.formattedTotal = ko.computed(function() {
return this.rate() * this.quantity();
}, this);
}
function documentViewModel(){
var self = this;
//create a mateirals array
self.materials = ko.observableArray([
new addMaterial()
]);
// Computed data
self.totalSurcharge = ko.computed(function() {
var total = 0;
for (var i = 0; i < self.materials().length; i++)
total += self.materials()[i].formattedTotal();
return total;
});
// Operations
self.addMaterial = function() {
self.materials.push(new addMaterial());
}
self.removeMaterial = function(material) { self.materials.remove(material) }
}
ko.applyBindings(new documentViewModel());
Here's my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script type='text/javascript' src='knockout-2.2.0.js'></script>
</head>
<body>
<div class="container">
<table class="table table-bordered">
<thead>
<tr>
<th>Item</th>
<th>Quantity </th>
<th>Rate</th>
<th>Total</th>
</tr>
</thead>
<tbody "foreach: materials">
<tr class="info">
<td><input data-bind="value: name" /></td>
<td><input data-bind="value: quantity" /></td>
<td><input data-bind="value: rate" /></td>
<td data-bind="text: formattedTotal"></td>
<td><a href="#" data-bind="click: $root.removeMaterial">Remove</a></td>
</tr>
</tbody>
</table>
<button data-bind="click: addMaterial, enable: materials().length < 5">Add Row</button>
<h3 data-bind="visible: totalSurcharge() > 0">
Total surcharge: $<span data-bind="text: totalSurcharge().toFixed(2)"></span>
</h3>
</div>
</body>
<script type='text/javascript' src='application.js'></script>
</html>
I have checked the console error in the browser but am not getting any errors. Any idea what I am doing wrong?
+3
source to share