Reputation: 862
Problem Description:
I am using knockout and I have a table. In this table, I have 3 columns. The first column has a drop down list. I want to generate a new row whenever a user chooses a value from a drop down list.
Here's my fiddle : http://jsfiddle.net/JPVUk/10/
<table class="table table-bordered">
<thead class="mbhead">
<tr class="mbrow">
<th>Type</th>
<th>Comment</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select class="input-small">
<option value="">Type</option>
<option value="">One</option>
<option value="">Two</option>
<option value="">Three</option>
</select>
</td>
<td><input class="input-small"/></td>
<td><input class="input-small"/></td>
</tr>
</tbody>
</table>
<button id="saveButton">save</button>`
I want to accomplish this using knockout. Is there a way to accomplish it using knockout?
Upvotes: 3
Views: 5129
Reputation: 3239
If I understand your question correctly, you want knockout to add a new row every time the selection in one of your dropdowns is changed.
You can do this by creating a view model with an observable array containing items. You then get your dropdown to insert items into it whenever the selection changes. See the following:
var ViewModel = function() {
var self = this;
self.items = ko.observableArray([{comment:'first comment', amount:0}]);
self.addNewItem = function(){
self.items.push(new Item('',0));
};
}
var Item = function(comment, amount) {
var self = this;
self.comment = ko.observable(comment);
self.amount = ko.observable(amount);
};
vm = new ViewModel()
ko.applyBindings(vm);
If you then add the following to your table markup:
<tbody data-bind="foreach: items">
<tr>
<td>
<select class="input-small" data-bind="event: { change: $root.addNewItem }">
<option value="">Type</option>
<option value="">One</option>
<option value="">Two</option>
<option value="">Three</option>
</select>
</td>
<td><input class="input-small" data-bind="value: comment"/></td>
<td><input class="input-small" data-bind="value: amount"/></td>
</tr>
</tbody>
I updated your JsFiddle here
Upvotes: 5