Newer Version Available

This content describes an older version of this product. View Latest

Which Button Was Pressed?

To find out which button was pressed in a component containing multiple buttons, use Component.getLocalId().
The framework provides two button components—ui:button and lightning:button.

We recommend that you use lightning:button, a button component that comes with Lightning Design System styling.

Note

Let’s look at an example with multiple ui:button components. Each button has a unique local ID, set by an aura:id attribute.

1<!--c:buttonPressed-->
2<aura:component>
3    <aura:attribute name="whichButton" type="String" />
4    
5    <p>You clicked: {!v.whichButton}</p>
6
7    <ui:button aura:id="button1" label="Click me" press="{!c.nameThatButton}"/>
8    <ui:button aura:id="button2" label="Click me too" press="{!c.nameThatButton}"/>
9</aura:component>

Use event.getSource() in the client-side controller to get the button component that was clicked. Call getLocalId() to get the aura:id of the clicked button.

1/* buttonPressedController.js */
2({
3    nameThatButton : function(cmp, event, helper) {
4        var whichOne = event.getSource().getLocalId();
5        console.log(whichOne);
6        cmp.set("v.whichButton", whichOne);
7    }
8})

If you’re using lightning:button, use the onclick event handler instead of the press event handler.

1<aura:component>
2    <aura:attribute name="whichButton" type="String" />
3    
4    <p>You clicked: {!v.whichButton}</p>
5
6    <lightning:button aura:id="button1" name="buttonname1" label="Click me" onclick="{!c.nameThatButton}"/>
7    <lightning:button aura:id="button2" name="buttonname2" label="Click me" onclick="{!c.nameThatButton}"/>
8</aura:component>
In the client-side controller, you 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.