0

I want to set the incremented value to lightning input when a button is pressed. In aura iteration n number of record when I click on a button it is copying the value to all lightning input. But in my case, I would like to set value only to the current input. I am getting the index but I am not able to set the value.

component :

<aura:component >    
    <aura:attribute name="quantity" type="String" default="0"/>
    <aura:attribute name="itemList" type="List" default="[1,2,3]"/>    
    <aura:iteration items="{!v.itemList}" var="prod" indexVar="index">
        <div data-index="{!index}" style="display:flex">
            <lightning:input value="{!v.quantity}" name="{!'itemQuantity_'+ index}" aura:id="itemInput"/>
            <lightning:button label="Add" onclick="{!c.addValue}" name="{!'itemQuantity_'+ index}"/>
        </div>
    </aura:iteration>
</aura:component>

Controller :

addValue : function(component, event, helper) {
  var selindex = event.target.dataset.index;
  var count = component.get("v.quantity");        
  count++;
  component.set("v.quantity", count);
}

enter image description here

1 Answer 1

0

You've set all the inputs to the same variable, so any change to one will affect them all. Imagine you wrote the following code:

let x = 5;
x = 10;

What is the value of x? Obviously, it's 10. To fix this, you need a list of values; which is what the iterator already has:

<lightning:input value="{!prod}" name="{!'itemQuantity_'+ index}" aura:id="itemInput"/>

Which you then set by modifying the list:

addValue: function(component, event, helper) {
  let itemList = component.get("v.itemList");
  let index = event.target.dataset.index;
  itemList[index]++;
  component.set("v.itemList", itemList);
}

You must log in to answer this question.

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