0

I try to get index, but it's always -1.

JS:

close : function(component, event, helper) {
    let vacancies = component.get("v.vacancies");  //an array
    let vacancy = event.getSource().get("v.name");  //name - the obct's Id from iteration

    const index = vacancies.indexOf(vacancy);        
    vacancies.splice(index, 1);        
    component.set("v.vacancies", vacancies);
},

cmp:

 <aura:iteration items="{!v.vacancies}" var="vacancy">
    <span class="spanButtonClose">
        <lightning:buttonIcon name="{!vacancy.Id}" iconName="utility:close" onclick="{!c.close}"/>
    </span>
</aura:iteration>

What is wrong here? It's just delete the last one object.

2 Answers 2

3

Aura:iteration has an attribute called as indexVar, why not use it?

Also from Event docs:

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.

Markup:

<aura:iteration items="{!v.vacancies}" var="vacancy" indexVar="index" >
    <span class="spanButtonClose">
        <lightning:buttonIcon name="{!index}" iconName="utility:close" onclick="{!c.close}"/>
    </span>
</aura:iteration>

JS Code:

close : function(component, event, helper) {
    let vacancies = component.get("v.vacancies");  //an array
    let toDeletIndex =  event.getSource().get("v.name");
    console.log(toDeletIndex );


    vacancies.splice(toDeletIndex, 1);        
    component.set("v.vacancies", vacancies);
},

Src: https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_cb_which_button_pressed.htm

2
  • Now it deletes only first element) alert(toDeletIndex); give me undefined Commented Jan 15, 2019 at 12:55
  • @YagamiRaito, Am sorry I posted bit incorrect code. I have updated it with references. Commented Jan 15, 2019 at 13:23
0

if vacancies.indexOf(vacancy) returns -1 means that the javascript didn't found the key on the array

may be check if you should have vacancy.id instead of vacancy.Id

2
  • Same. It's JS case sensitive, not lightning's component. Commented Jan 15, 2019 at 12:34
  • It's also alert the right Id, so... The problem is in another place. I just don't know, can we use the name of an element for indexOf or not. Commented Jan 15, 2019 at 12:36

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.