Get Index in jQuery template
Asked Answered
C

2

8

I am using the jQuery template plugin and don't know how to get the index of items: http://api.jquery.com/category/plugins/templates/

Here is my code:

<script id="optionTmpl" type="text/x-jquery-tmpl">
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
    {{each Answers}}
        <tr>
            <th><input type="radio" name="group1" value="${this.AnswerID}" /></th>
            <td>${this.AnswerText}</td><!-- add number in this line--->
        </tr>
    {{/each}}  
    </table>
</script>

I want to show the answer in the format like the following

1)answer1, 2)answer2, 3)answer3

or

a)answer1, b)answer2, c)answer3

What should I do?

Commorant answered 18/11, 2010 at 8:53 Comment(0)
M
23

There's an implicit $index (and $value) available inside the {{each}} loop, you can use that here:

<script id="optionTmpl" type="text/x-jquery-tmpl">
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
    {{each Answers}}
        <tr>
            <th><input type="radio" name="group1" value="${this.AnswerID}" /></th>
            <td>${this.AnswerText} ${$index + 1}</td>
        </tr>
    {{/each}}  
    </table>
</script>

You'll probably want to add 1 because it's 0-based, like I have above.

Maros answered 18/11, 2010 at 9:20 Comment(0)
G
0

I hope this code will help you to get the index in jQuery template:-

$("#optionTmpl").tmpl(data, {
  dataArrayIndex: function (item) {
    return $.inArray(item, data);
  }
}).appendTo("#TableBody");

You can use this ${$item.dataArrayIndex($item.data)} to get the current index

<script id="optionTmpl" type="text/x-jquery-tmpl">
  <table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <th><input type="radio" name="group1" value="${AnswerID}" /></th>
      <td>${AnswerText} ${$item.dataArrayIndex($item.data)}</td>
    </tr>
  </table>
</script>
Gallipot answered 3/8, 2023 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.