What is the correct way to pass Parameters to Lightning JS controller from UI:Button?

  • I have a button in a table in lightning component. I'm trying to get clicked id of the record.

    Component markup

        <table class="slds-table slds-table--bordered slds-table--striped slds-table--cell-buffer slds-table--fixed-layout">
                <tr class="slds-text-heading--label">
                    <th scope="col">
                        <div class="slds-truncate" title="Name">Name</div>
                    <th scope="col">
                        <div class="slds-truncate" title="Remove">Remove</div>
                <aura:iteration items="{!v.Items}" var="item">
                            <div class="slds-truncate" title="{!item.Name}">{!item.Name}</div>
                            <form onclick="{!c.removeItem}">
                                <input type="hidden" class="prodclass" value="{!item.Id}" id="{!item.Id}"  />
                                <lightning:button label="Remove" iconName="utility:delete" iconPosition="left" variant="destructive" value="{!item.Id}"/>

    JS Controller

    removeItem: function(component, event, helper) {
        var id_str = event.target.getElementsByClassName('prodclass')[0].value;

    I'm getting error,

    ElementsByClassName is not a function

    Appreciate any help on this. Thanks.

    document.getElementsByClassName('prodclass')[0].value returns the value, so the issue is not with getElementsByClassName are you sure you are sharing all your code, why are you using event.target? can you share your event, if any?

    @glls Thanks. it's a simple button call. No event involved. I'm trying to get event's parameters to read the current record Id.

  • There is no need for a form in your td.

    Wrap your button in a div, attach the value to the div via a data- attribute and grab it from the event.currentTarget. Eg:

    <div onclick="{!c.removeItem}" data-value="123">
        <lightning:button label="Remove" iconName="utility:delete" iconPosition="left"  variant="destructive" value="123"/>

    Controller method:

    removeItem: function(component, event, helper) {
        var ctarget = event.currentTarget;
        var id_str = ctarget.dataset.value;

    An additional point is that for `data-stageName="123"` you might expect `ctarget.dataset.stageName` to work. But the name gets mapped to lowercase so it has to be `ctarget.dataset.stagename`. So best to avoid camel-casing in the name.

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM