Knockoutjs.com - Grid editor example
http://knockoutjs.com/examples/gridEditor.html
by KevinGabbert
HTML
<script src="http://knockoutjs.com/js/jquery.validate.js"></script>
<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
<div class='liveExample'>
<form action=''>
<p>You have asked for <span data-bind='text: roles().length'> </span> roles(s)</p>
<table data-bind='visible: roles().length > 0'>
<thead>
<tr>
<th>Role</th>
<th>Physician</th>
<th />
</tr>
</thead>
<tbody data-bind='foreach: roles'>
<tr>
<td><input class='required' data-bind='value: role, uniqueName: true' /></td>
<td><input class='required' data-bind='value: physician, uniqueName: true' /></td>
<td><a href='#' data-bind='click: $root.removeRole'>Delete</a></td>
</tr>
</tbody>
</table>
<button data-bind='click: addRole'>Add Role</button>
<button data-bind='enable: roles().length > 0' type='submit'>Submit</button>
</form>
</div>
CSS
body { font-family: arial; font-size: 14px; }
.liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
.liveExample input { font-family: Arial; }
.liveExample b { font-weight: bold; }
.liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; }
.liveExample select[multiple] { width: 100%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; font-weight: bold; font-size: 1.2em; }
.liveExample table, .liveExample td, .liveExample th { padding: 0.2em; border-width: 0; }
.liveExample td input { width: 13em; }
tr { vertical-align: top; }
.liveExample input.error { border: 1px solid red; background-color: #FDC; }
.liveExample label.error { display: block; color: Red; font-size: 0.8em; }
.liveExample th { font-weight: bold; }
li { list-style-type: disc; margin-left: 20px; }
JavaScript
var RolesModel = function(roles) {
var self = this;
self.roles= ko.observableArray(roles);
self.addRole = function() {
self.roles.push({
role: "",
physician: ""
});
};
self.removeRole = function(role) {
self.roles.remove(role);
};
self.save = function(form) {
alert("Could now transmit to server: " + ko.utils.stringifyJson(self.roles));
// To actually transmit to server as a regular form post, write this: ko.utils.postJson($("form")[0], self.gifts);
};
};
var viewModel = new RolesModel([
{ role: "Attending Surgeon", physician: "AVARA, WILLIAM TRAVIS III"},
{ role: "Admitting Physician", physician: "AVARA, WILLIAM TRAVIS III"}
]);
ko.applyBindings(viewModel);
// Activate jQuery Validation
$("form").validate({ submitHandler: viewModel.save });