Take the 2-minute tour ×

I have the following table template that is rendered through knockout:

            <table class="gv" data-bind="visible: products().length > 0">
                <tbody data-bind="foreach: products">
                    <tr data-bind="click: $root.selectProduct">
                        <td data-bind="text: type"></td>

Now I want to make the rows clickable and want to assign a css class if a row is selected. Only 1 (!) row could be selected at a time, so others have to be unchecked.

The simplest way would be to extend my model (product class) with a selected property but this would destroy my 1:1 mapping with the server side.

How should I solve this issue? How would you handle this?

share|improve this question
add comment

2 Answers

up vote 12 down vote accepted

This was my final solution now, no extra hidden radio buttons:

<tr data-bind="click: $root.selectProduct, css: { 'active-row': $root.selectedProduct() === $data }">

And the selectedProduct implementation within the ViewModel:

function AppViewModel() {
    // Private
    var self = this;

    // Public Properties
    self.selectedProduct = ko.observable();
share|improve this answer
For completeness of answer, I'd love to see selectProduct defined. –  TelegramSam May 22 '12 at 16:23
@TelegramSam A bit late but here it is. –  timmkrause Jun 25 '12 at 10:50
@jtkrause Why is your selectProduct property an observableArray and not an observable only - an object - when you allow only single selection? –  Elisa Apr 29 '13 at 11:56
That is a good question! ;-) I will correct it. –  timmkrause May 6 '13 at 12:32
what happens if the user tabs into this row? –  Peter Munnings Jul 28 '13 at 17:39
show 3 more comments

You could add a hidden radio button group to the table, and when the row is selected calling selectProduct the radio button is selected.

This ensures that only one row is selected.

Alternatively you could write a custom binding using the jQuery .data() to specify the selected row.

share|improve this answer
The radio button sounds good and it uses standard browser/html techniques to handle the unique selection. Would you also prefer this solution? –  timmkrause Mar 26 '12 at 12:00
That's how I would tackle it first - but I would be aware that if, in the future, I required multiple selection, I would have to rewrite it. –  Macropus Mar 26 '12 at 12:01
This will definitely not happen! Thank you! –  timmkrause Mar 26 '12 at 12:04
Mh, can you give me a quick example? With "<td><input type="radio" name="activeproduct" /></td>" I´m not able to select any of those radio buttons. And how do I bind the css binding to a checked radio button? jQuery? –  timmkrause Mar 26 '12 at 12:25
Select the radio button in the selectProduct function programatically [stackoverflow.com/questions/977137/…. As the radio button will be part of the activeproduct group, only one will be selectable. –  Macropus Mar 27 '12 at 11:10
add comment

Your Answer


