0

I need to uncheck the checkbox on click of a button, but I'm using the checkbox inside the aura:iteration and on using aura:id I'm getting the value as undefined. My Actual Scenario is like there are multiple buttons, if I click on a button, checks the checkbox and then click on the cancel button and click on another button, the checkboxes which I checked earlier retains.

<aura:iteration items = "{!v.UserWrapper}" var = "col" indexVar = "index">
                <aura:if isTrue = "{!v.Segment == col.segment}">
                    <tr class="{! (index%2)==0?'':'altRow'}">
                        <th scope="row" width = "10%">
                            <div class="slds-truncate">
                                    <lightning:input type="checkbox" aura:id="checkboxField" onchange = "{!c.OnRemove}"/>
                            </div>
                        </th>
                    </tr>
                </aura:if>
            </aura:iteration>

CloseNav: function(component, event, helper) { // function called on Cancel button
        var checkBxVal = component.find('checkboxField').set("v.checked", false); // checkBxVal => undefined
        component.set("v.display", false);
}

1 Answer 1

1

You need to check if you have an Array or not.

var checkboxes = component.find("checkboxField");
if(checkboxes && !checkboxes.length) { // is an object, not an Array
    checkboxes = [checkboxes]; // Make this an array
}
if(checkboxes) {
    // Uncheck all boxes //
    checkboxes.forEach(function(cmp)) {
        cmp.set("v.checked", false);
    });
} 

Find can return one of three possible values.

  • undefined means there are no matches.
  • SecureComponent means there was exactly one match.
  • Array means there were two or more matches.

So, the code above converts the second condition into an Array, so we're left with either undefined or an Array, and we can then iterate over the Array and set the attributes.

2
  • @ sfdcfox thanks for Proactive response, var checkboxes = component.find("v.checkboxField") is always returning undefined irrespective of the aura:id and therefore its never satisfying any of the condition, my concern is there any way to get the values using aura:id inside aura:iteration?
    – Abhishek56
    Apr 22, 2020 at 6:08
  • @AbhishekGangwar Sorry, it should have been just checkboxField. The v. was a typo.
    – sfdcfox
    Apr 22, 2020 at 10:17

You must log in to answer this question.

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