Bronzato
Bronzato

Reputation: 9332

Highlight rows of my table where checkbox is checked with knockout

I have an html table with a checkbox on first column. I would like to highlight the row where checkboxes are checked with knockout.

<table class="defaultGrid">
<thead>
    <tr>
        <th>Check</th>
        <th>ID</th>
        <th>Name</th>
    </tr>
</thead>
<tbody data-bind="foreach: model.Things">
    <tr>
        <td><input type="checkbox" data-bind="click: $root.selectThing " /></td>
        <td data-bind="text: ID"></td>
        <td data-bind="text: Name"></td>
    </tr>
</tbody>
</table>

Here is an example on jsFiddle: http://jsfiddle.net/jJ4H6/1/

I don't know how to proceed. I don't want to add an extra property on my model like 'isSelected'.

Any idea?

Thanks.

Upvotes: 0

Views: 1181

Answers (2)

Rune Vejen Petersen
Rune Vejen Petersen

Reputation: 3239

I would definitely add a knockout observable to your 'Thing' that determines whether or not your tr element has a yellow background or not.

However, if you really don't want to add something like this to your view model, you'll have to add some logic to your selectThing function to handle this for you e.g.

self.selectThing = function(item, event) {
        $(event.target).parent().parent().addClass('selected');
   }; 

Upvotes: 1

Darussian
Darussian

Reputation: 1593

Check out this Jfiddle http://jsfiddle.net/jJ4H6/27/

 $(function() {
Thing = function(id, name, selected) {
    var self = this;
    self.ID = id, 
    self.Name = name
    self.isChecked = ko.observable(false);
};

function viewModel() {
    var self = this;
    self.model = {};
    self.model.CurrentDisplayThing = ko.observable();
    self.model.Things = ko.observableArray(
        [
            new Thing(1, "Thing 1"),
            new Thing(2, "Thing 2"),
            new Thing(3, "Thing 3")
        ]);
    self.selectThing = function(item) {

    };
}
ko.applyBindings(new viewModel());

});

Upvotes: 1

Related Questions