0

I have a list of items that are being set on the initialization of my component. Then I'm iterating over the list of items and and for each item, I'm creating a checkbox with the description of the item. If one is selected, I want to know the index of the item in the list and remove it from the list.

<aura:iteration items="{!v.items}" var="item">
  <lightning:input aura:id="checkbox" label="{!item.des}" type="checkbox" onchange="{!c.removeTask}">
</aura>

How do I get the index value and then use that index value against my items list to remove the specific item?

1 Answer 1

1

You can use the indexVar attribute to set the index to the name of the checkbox and use that.

Component.

<aura:component >
    <aura:attribute name="items" type="List" />

    <aura:handler name="init" value="{!this}" action="{!c.init}"/>

    <aura:iteration items="{!v.items}" var="item" indexVar="index" >
        <lightning:input aura:id="checkbox" name="{!index}" label="{!item.des}" type="checkbox" onchange="{!c.removeTask}" />
    </aura:iteration>

</aura:component>

Controller

({
    init : function(component, event, helper) {
        var myItems = [];
        var myItem1 = {};
        var myItem2 = {};

        myItem1['des'] = 'Label 1';
        myItem2['des'] = 'Label 2';

        myItems.push(myItem1);
        myItems.push(myItem2);

        component.set('v.items', myItems);
    },

    removeTask : function(component, event, helper) {        
        var index = event.getSource().get("v.name");
        var myItems = component.get('v.items');
        myItems.splice(index, 1);
        component.set('v.items', myItems);
    }
})
1
  • Worked like a charm :) Thanks! Aug 23, 2019 at 18:49

You must log in to answer this question.

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