1

I get used to use jQuery when I develop Visualforce. Looks like jQuery doesn't work with Lightning. I am trying to get index of < tr> element clicked in table element using Ligtnening.

I would assume this code to work

jQuery(event.currentTarget).index()

but this returns -1. In Visualforce

jQuery(this).index()

returns me index of current tr element.

I don't want to use data-index property because I don't want to make this more complicated and create additional model around SObject record which I don't really need here.

Currently I am thinking about some code like this

var trs = $('table.labels').find('tr');
        var index;
        for ( var i = 0; i < trs.length; i++ ) {
            if ( trs[i] == event.currentTarget ) {
                index = i;
                break;
            }
        }

but it looks to me really ugly and cumbersome.

Does anyone know any better and more elegant solution?

Thanks.

2
  • 1
    To use data-index, you don't need to modify your model if you are using aura:iteration.Check this answer.How are you generating the table?
    – Praveen
    Aug 23, 2016 at 9:42
  • trying to adopt that approach...
    – Patlatus
    Aug 23, 2016 at 12:20

1 Answer 1

3

I actually had aura:iteration tag like this

<aura:iteration items="{!v.projects}" var="project">
<tr onclick="{!c.labelClick}">
<td title="{! project.Name }">
{! project.Name }
</td>
</tr>
</aura:iteration>

One more guy (besides of Praveen) also suggested to use indexVar and data-index.

<aura:iteration items="{!v.projects}" var="project"indexVar="index">
<tr data-index="{!index}"  onclick="{!c.labelClick}">
<td title="{! project.Name }">
{! project.Name }
</td>
</tr>
</aura:iteration>
enter code here

so this helps to use some code like this:

var index = event.currentTarget.dataset.index;

The only drawback of this approach is that data-index property is String, instead of Integer, but looks like it still works even being String at least for my case.

3
  • 1
    I would if I could. When I try it shows red alert and says: "You can accept your own answer in 2 days"
    – Patlatus
    Aug 23, 2016 at 12:35
  • Ok Patlatus, Please mark it after 2 days. Thanks
    – Praveen
    Aug 23, 2016 at 12:43
  • Using data is an excellent approach.
    – JF Paradis
    Aug 23, 2016 at 20:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .