4

I want to get index variable of products array record in controller on which user clicked. I am trying to get this by event.target.dataset.index. But event.target.dataset.index gives undefined. The code is as below:

Component

<ul>
<aura:iteration items="{!v.products}" var="product" indexVar="index">
    <li onclick="{!c.ShowDataOnClick}" data-row-index="{!index}">
        <p>{!product.Name}</p>
        <p>{!product.ProductCode}</p>
    </li>
</aura:iteration></ul>

Controller

ShowDataOnClick: function(component, event, helper) {
    var index = event.target.dataset.index;
    console.log(index);
}
3
  • Try assigning index to a label attribute of <li> and access it in controller like this: event.getSource().get("v.label"); Commented Jul 21, 2017 at 8:52
  • Hi Rohit, console returns: event.getSource is not a function. Commented Jul 21, 2017 at 9:10
  • 1
    Hope this helps: event-getsource-on-onclick-from-li Commented Jul 21, 2017 at 9:45

2 Answers 2

9

Component:

<aura:application >
    <ul>
        <aura:iteration items="[1,2,3,4]" var="product" indexVar="index">
            <li onclick="{!c.ShowDataOnClick}" data-row-index="{!index}">
                <p>{!product}</p>
                <p>{!product}</p>
            </li>
        </aura:iteration></ul>
</aura:application>

use currentTarget instead of target

controller:

 ({
        ShowDataOnClick: function(component, event, helper) {
           var index = event.currentTarget.dataset.rowIndex;
            console.log(index);
        }
    })
8
  • Already tried. event.currentTarget gives Proxy {} and event.currentTarget.dataset.index gives undefined. Commented Jul 21, 2017 at 9:32
  • I have tried just I am getting value correctly .open the proxy object see dataset check whether its have a index.
    – vignesh
    Commented Jul 21, 2017 at 9:36
  • Hi, I open proxy object. It show the following value in dataset. dataset:Proxy -> [[Handler]]:a -> proto:Object -> [[Target]]:d -> [[IsRevoked]]:false Commented Jul 21, 2017 at 9:41
  • Proxy {$actual$: DOMStringMap} [[Handler]] : a [[Target]] : d $actual$ : DOMStringMap auraRenderedBy : "15:0" index : "2" proto : DOMStringMap proto : Object [[IsRevoked]] : false
    – vignesh
    Commented Jul 21, 2017 at 9:43
  • 1
    No. No sign of index. Commented Jul 21, 2017 at 9:44
0

I had the same issue. The issue is that the event parameter changes depending on the element being clicked.

So if you are clicking on {!product} and it is firing the function on the parent li element, the event parameter for the parent function is actually set to the p element of the product.

There should be a way to get the exact element triggering the function, especially when we cannot manually set function input parameters.

EDIT: Turns out you can, use event.currentTarget instead of event.target.

You must log in to answer this question.

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