0

I want to count the position of table children using jQuery in a Meteor JS helper function, but I always get an empty result, because the helper function returns before the table data gets inserted.

Here is my code:

<table class="table">
                <thead>
                <tr>
                    <th>#</th>
                    <th>Game</th>
                </tr>
                </thead>
                <tbody>
                    {{#each games}}
                        {{> game}}
                    {{/each}}
                </tbody>
</table>


    <template name="game">
        <tr>
            <td>{{counter}}</td>
            <td>{{name}}</td>
        </tr>
    </template>

Template.game.helpers({
    counter: function() {
        return $('table.table tbody tr td:contains("this.name")').index();
    }
});

It should be like: 1 Test 2 ABC 3 HelloWorld ...

Any help would be greatly appreciated.

user3475602
  • 1,217
  • 2
  • 21
  • 43
  • 1
    How you are rendering that table ? Your selector seems to be invalid, try this: `return $('table.table tbody tr td:contains("'+this.name+'")').index();` – Kuba Wyrobek Sep 10 '14 at 18:52
  • Thank you for your help! But now I get 1 for every entry and it should be in descending order. Is it possible to achieve this with `index()`? – user3475602 Sep 10 '14 at 18:59
  • Without seeing rest of code it is hard to say. It is better to operate on data instead using jquery tricks like here. Please show me how you generate table (templates, route, data) ? – Kuba Wyrobek Sep 10 '14 at 19:04
  • I edited my post, so you can see how I generate the table. However, I don't know how to operate on data, since I also want to add dynamically table data with jQuery. – user3475602 Sep 10 '14 at 19:27

1 Answers1

3

The idea for solution is that you add to array of games objects additional field called index. Later in game template you simply use {{index}}.

Below code should solve your issue:

var games_with_index = Games.find().map(function(document, index){
    document.index = index;
    return document;
});

<table class="table">
   <thead>
        <tr>
            <th>#</th>
            <th>Game</th>
        </tr>
    </thead>
    <tbody>
        {{#each games_with_index}}
          {{> game}}
        {{/each}}
    </tbody>
</table>

<template name="game">
    <tr>
        <td>{{index}}</td>
        <td>{{name}}</td>
    </tr>
</template>

See also this: Print the loop index in Meteor.js templates

Community
  • 1
  • 1
Kuba Wyrobek
  • 5,273
  • 1
  • 24
  • 26