我正在尝试使用选择列表的值进行计算,但在选择它时我无法让它检索数字。
当我返回所选数量时,它会返回一些 javascript 而不是数字
selectedQuantity 是我要检索的值。
<table border="1">
<thead><tr>
<th>ID</th><th>Inventory</th><th>Quantity</th><th>Price</th><th>Total</th><th></th>
</tr></thead>
<tbody data-bind="foreach: itemNumbers">
<tr>
<td data-bind="text: ID"></td>
<td data-bind="text: inventory"></td>
<td><select data-bind="quantityDropdown: inventory, value: selectedQuantity"></select></td>
<td data-bind="text: formattedPrice"></td>
<td data-bind="text: itemTotal"></td>
<td><a href="#" data-bind="click: $root.removeItem">Remove</a></td>
</tr>
</tbody>
</table>
这是javascript
function ItemEntry(ID, inventory, price) {
var self = this;
self.ID = ID;
self.inventory = inventory;
self.price = price;
self.selectedQuantity = ko.observable(); //returned value (trying to get it at least!)
self.itemTotal = ko.computed(function() {
var price = self.price;
var quantity = self.selectedQuantity;
return quantity; //just returning quantity for now to verify correct value is selected
});
self.formattedPrice = ko.computed(function() {
var price = self.price;
return price ? "$" + price.toFixed(2) : "None";
});
}
function EntryViewModel(newItem) {
var self = this;
self.newItem = newItem;
//start the array with some items
self.itemNumbers = ko.observableArray([
new ItemEntry("1", 20, 22.50) //ID, inventory, price
]);
// Computed data
self.totalCost = ko.computed(function() {
var total = 0;
for (var i = 0; i < self.itemNumbers().length; i++) {
total += Number(self.itemNumbers()[i].price);
}
return total;
});
self.removeItem = function(item) { self.itemNumbers.remove(item) }
}
//populate the select list with values up to the number in inventory (ex, if inventory is 3, it will fill with 0-7)
ko.bindingHandlers.quantityDropdown = {
update: function(quantityDropdown, inventory, EntryViewModel) {
var quantity = ko.utils.unwrapObservable(inventory());
for(var i = 0; i <= inventory(); i++){
$(quantityDropdown).append('<option value="' + i + '">' + i + '</option>');
}
}
};
ko.applyBindings(new EntryViewModel());