Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table row number when binding knockout foreach

Tags:

knockout.js

I have a table with headers(#,User name,User surname) and is doing a knockout foreach loop to add the rows when the user select the user name from a checkbox list. Here is my Fiddle.

HTML

<div>
    <table class="table table-bordered">
       <thead>
           <th>#</th>
           <th>User Name</th>
           <th>User Surname</th>
       </thead>
       <tbody data-bind="foreach: users">
           <tr data-bind="if: userselected">
               <!-- The table row number -->
               <td data-bind="text: $index() + 1"></td>
               <td data-bind="text: username"></td>
               <td data-bind="text: usersurname"></td>
           </tr>
       </tbody>
   </table>
</div>

JS

var myViewModel = {
     users: ko.observableArray([{
         username: 'Name 1',
         usersurname: 'Surname 1',
         userselected: ko.observable(false)
     }, {
         username: 'Name 2',
         usersurname: 'Surname 2',
         userselected: ko.observable(false)
     }, {
         username: 'Name 3',
         usersurname: 'Surname 3',
         userselected: ko.observable(false)
     }])
 };

 $(document).ready(function () {
     //Bind View model
     ko.applyBindings(myViewModel);
 });

The problem comes in when the user selects users 1 and 3 the $index() + 1 doesn't work for the row number.

I need a way to set the row number dynamically.

Thanks in advance.

like image 456
Juan Gous Avatar asked Mar 07 '13 10:03

Juan Gous


1 Answers

I would create a computed observable where I do the filtering. Then the $index() will provide the correct rownumbers:

So add a new property selectedUsers to your myViewModel:

myViewModel.selectedUsers = ko.computed(function () {
     return ko.utils.arrayFilter(myViewModel.users(), function (item) {
         return item.userselected();
     });
 });

Then bind to it in your table:

<tbody data-bind="foreach: selectedUsers">
        <tr>
            <!-- The table row number -->
            <td data-bind="text: $index() + 1"></td>
            <td data-bind="text: username"></td>
            <td data-bind="text: usersurname"></td>
        </tr>
</tbody>

Demo JSFiddle.

like image 161
nemesv Avatar answered Sep 28 '22 05:09

nemesv