To find out which button was clicked in a component containing multiple buttons, we can use Component.getLocalId()
.
Here is an example with multiple lightning:button
components. Each button has a unique local ID, set by an aura:id
attribute.
Sample Lightning Component:
<!--Sample.cmp--> <aura:component> <aura:attribute name="clickedButton" type="String" /> <div class="slds-m-around_xx-large"> <p><b>You Clicked: {!v.clickedButton}</b></p> <br/> <lightning:button aura:id="button1" name="btn1" label="Click Me" onclick="{!c.buttonClick}"/> <lightning:button aura:id="button2" name="btn2" label="Click Me" onclick="{!c.buttonClick}"/> </div> </aura:component>
In the JS controller, we can use one of the following methods to find out which button was clicked.
event.getSource().getLocalId()
returns the aura:id of the clicked button.
event.getSource().get("v.name")
returns the name of the clicked button.
Sample Lightning Component JS Controller:
({ buttonClick : function(cmp, event, helper) { var clickedBtn = event.getSource().getLocalId(); alert(clickedBtn); cmp.set("v.clickedButton", clickedBtn); } })
Lightning Test App:
<!--Test.app--> <aura:application extends="force:slds"> <c:Sample /> </aura:application>