[SalesForce] Getting only the contacts whose checkbox is true in salesforce1 lightning

I am displaying a list of contacts through "aura:iteration" with a checkbox inside it. I want to get the contact ids for the selected contacts.

For example

<aura:attribute name ="someContacts" type="Contact[]"/>

<aura:Iteration name="{!v.somContacts}" var="con">
   <ui:inputCheckbox>
   {!con.Name}
</aura:iteration>

The above code displays a check box each contact . I want to get the checked contact ids.

Best Answer

You'll need to set the value on each checkbox to be the Id of the contact, like this:

<aura:attribute name="contacts" type="Contact[]" />
<aura:attribute name="checkedContacts" type="String[]" />

<aura:iteration var="con" items="{!v.contacts}">
  <ui:inputcheckbox text="{!con.Id}" label="{!con.Name}" change="{!c.updateCheckboxes}"/>
</aura:iteration>

Then use a client-side handler either on each checkbox or on a button to check whether each checkbox is checked and add its value (the contact Id) to an array. For example, here's my updateCheckboxes handler:

updateCheckboxes : function(component, event) {
  var id = event.source.get("v.text");
  if (event.source.get("v.value")) {
    // Checkbox is checked - add id to checkedContacts
    if (component.get("v.checkedContacts").indexOf(id) < 0) {
      component.get("v.checkedContacts").push(id);
    }
  } else {
    // Checkbox is unchecked - remove id from checkedContacts
    var index = component.get("v.checkedContacts").indexOf(id);
    if (index > -1) {
      component.get("v.checkedContacts").splice(index, 1);
    }
  }
}

(PS: It's important to use the ui:inputcheckbox label attribute to set the label, and not just stick it next to the checkbox in the component markup. ui:inputcheckbox will programmatically associate the label with the checkbox properly, making the label accessible to assistive technologies like screen readers. All the basic components have been carefully built to be accessible like this, so you get it for free as long as you use them correctly.)

Related Topic