ノックアウト テーブルに数量選択オプションがありますが、利用可能な在庫に基づいて上限を設定したいと考えています。
エントリに次の値があるとします
ID = 1
stock = 8
数量フィールドに 1 ~ 在庫、この場合は 1 ~ 8 の数字を入力します。数量は常に在庫以下になります。
function ItemEntry(ID, stock, quantity) {
var self = this;
self.ID= ID;
self.stock= stock;
self.quantity = quantity;
}
// viewmodel
function EntryViewModel() {
var self = this;
self.itemNumbers = ko.observableArray([
new ItemEntry("1", 8, QUANTITY HERE!) //initial starting values
]);
self.removeItem = function(item) { self.itemNumbers.remove(item) }
}
//custom binding for dropdown outside of models
ko.bindingHandlers.quantityDropdown = {
update: function(quantityDropdown, stock, EntryViewModel) {
var quantity = ko.utils.unwrapObservable(stock());
for(var i = 0; i < stock(); i++)
{
$(quantityDropdown).append('<option value="' + i + '">' + i + '</option>');
}
}
};
ko.applyBindings(new EntryViewModel());
ここにHTMLがあります
<table border="1">
<thead><tr>
<th>ID</th><th>Stock</th><th>Quantity</th><th></th>
</tr></thead>
<tbody data-bind="foreach: itemNumbers">
<tr>
<td data-bind="text: ID"></td>
<td data-bind="text: stock"></td>
<td><select data-bind="quantityDropdown: quantity"></select></td>
<td><a href="#" data-bind="click: $root.removeItem">Remove</a></td>
</tr>
</tbody>
</table>