rafn
rafn

Reputation: 69

How to highlight a table row using style binding?

I need to show a details view based on a selected row in a table. I would like to show which row is currently selected in the table. Is it possible to do this with the 'style' binding?

I've created a JSFidle with some code illustrating the idea...or lack of, since it currently all rows change color on row click. Here's the code:

<table>
   <tr>
       <th>Name</th>
       <th>Sales</th>
       <th>Price</th>
    </tr>
  <tbody data-bind='template: { name: "fieldTemplate", foreach: viewModel.items}'></tbody>
</table>


<script type="text/html" id="fieldTemplate">
    <tr >
         <td> ${name}</td>
         <td>${sales}</td>
         <td>${price}</td>
    </tr>
</script>

And this is the Javascript:

var viewModel = {
    items: ko.observableArray([
            { name: "Well-Travelled Kitten", sales: 352, price: 75.95 },
            { name: "Speedy Coyote", sales: 89, price: 190.00 },
            { name: "Furious Lizard", sales: 152, price: 25.00 },
            { name: "Indifferent Monkey", sales: 1, price: 99.95 },
            { name: "Brooding Dragon", sales: 0, price: 6350 },
            { name: "Ingenious Tadpole", sales: 39450, price: 0.35 },
            { name: "Optimistic Snail", sales: 420, price: 1.50 }
        ])
};  

So I think I need a reference to the current row, or adding a style attribute to my item and then bind to this, and then change in the click event. Any ideas?

Upvotes: 3

Views: 3603

Answers (2)

neeebzz
neeebzz

Reputation: 11538

You'll need to bind a click event to each row of the table. Once a row is clicked. then in the event handler you can change the color of the selected row + you can show the new details

something like this > http://jsfiddle.net/wrzFx/11/

Upvotes: 3

I would bind a selection event on a table row via jQuery live events. Inside the listener I would change the value of selectedRow attribute in your viewModel

That might not sound a Knockout way to do things but as long as it works I'm ok with it.

BTW, I can't get jQuery templates running inside jsFiddle for some reason.

Upvotes: 2

Related Questions