I'm using KO.js to bind a table body with many rows. The first column has some buttons, if user clicks on a button of a row, I want that row be highlighted. But I don't know how to reference to the table row from Ko's binding method.
here's the fiddle I'm talking about.
and some code:
<table class="table table-bordered">
<tbody data-bind="foreach: frameworks">
<td>
<button class=btn data-bind="click: $parent.doStuff">A</button>
</td>
<td data-bind="text: $data"></td>
</tbody>
</table>
var App = new function () {
var self = this;
self.frameworks = ko.observableArray();
self.doStuff = function () {
//how to change table row color?
};
};
App.frameworks.push('bootstrap');
App.frameworks.push('knockout.js');
ko.applyBindings(App);
You are close. I have updated your fiddle here with the solution.
HTML
<table class="table table-bordered">
<tbody data-bind="foreach: frameworks">
<tr data-bind="css: {'selected':$root.selectedItem() == $data}">
<td>
<button class=btn data-bind="click: $root.doStuff">A</button>
</td>
<td data-bind="text: $data"></td>
</tr>
</tbody>
</table>
CSS
.selected
{
background-color:red;
}
Javascript
var App = new function () {
var self = this;
self.frameworks = ko.observableArray();
self.selectedItem = ko.observable(null);
self.doStuff = function (item) {
self.selectedItem(item);
//do other things here for the button click
};
};
App.frameworks.push('bootstrap');
App.frameworks.push('knockout.js');
ko.applyBindings(App);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With