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.

4
  • 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(); Sep 10, 2014 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()? Sep 10, 2014 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) ? Sep 10, 2014 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. Sep 10, 2014 at 19:27

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.