Knockout - Row highlighting
by johnpapa
HTML
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.js"></script>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Value</th>
</tr>
</thead>
<tbody data-bind="foreach: Configs">
<tr data-bind="click: $parent.SelectConfig, css: { selected: isSelected }">
<td data-bind="text: Name"></td>
<td data-bind="text: Value"></td>
</tr>
</tbody>
</table>
<br />
<div data-bind="with: Selected">
<label for="name">Selected.Name</label>
<input type="text" id="name" data-bind="value: Name" />
<label for="value">Selected.Value</label>
<input type="text" id="value" data-bind="value: Value" />
<input type="button" data-bind="click: $root.AddConfig" value="Add config" />
</div>
CSS
.selected { background-color: yellow; }
JavaScript
function Config(name, value, selected) {
var self = this;
self.Name = ko.observable(name);
self.Value = ko.observable(value);
self.isSelected = ko.computed(function(){
return selected() === self;
});
}
function ConfigsViewModel() {
var self = this;
this.Selected = ko.observable();
this.Configs = ko.observableArray([
new Config("Name 1", 10, this.Selected),
new Config("Name 2", 20, this.Selected)
]);
this.SelectConfig = function(config) {
self.Selected(config);
};
this.AddConfig = function() {
self.Configs.push(new Config("Added", 11));
};
this.Selected(this.Configs()[0]);
}
ko.applyBindings(new ConfigsViewModel());
/*
//Yet another option sans binding
$(".clickableRow").on("click", function() {
$(".clickableRow").css("backgroundColor", "transparent");
$(this).css("backgroundColor", "red");
//show the details related to the selected row here
});
*/