1

I have a lightning component that looks like this:

<aura:iteration items="{!v.categories}" var="category">
    <li data-category-id="{!v.category.Id}">
       <ui:inputCheckbox change="{!c.selectCategory}"/>
    </li>
</aura:iteration>

And I need to get the Id value in my controller. I've looked at examples, but properties and functions are never available on the event I'm receiving.

dataset isn't available, parentNode isn't available,... it feels like I'm having to fight the framework to do something that should be incredibly simple. What is the correct way to handle a situation like this?

2 Answers 2

3

You can store categoryId either in name or class of ui:inputCheckbox and access it via :

event.getSource().get("v.name") - for name

or

event.getSource().get("v.class") - for class

component:

<aura:iteration items="{!v.categories}" var="category">
    <li>
       <ui:inputCheckbox change="{!c.selectCategory}" name="{!category.Id}"/>
    </li>
</aura:iteration>

Controller:

selectCategory : function(cmp, event, helper) {
    var catId = event.getSource().get("v.name");
}

For more reference check the doc of ui:inputCheckbox

2
  • +1, but using "name" is a bad idea, as it has semantics in HTML (esp. re. ui:inputRadio), and value should ideally be bound to a Boolean value to check the state of the field (checked/unchecked). Unfortunately, this means there's no good attributes left, which is why I usually suggest hooking a parent element's event handler instead.
    – sfdcfox
    Commented Apr 20, 2018 at 7:08
  • I agree with the usage of "name" though it's not clean still, there are scenarios you need to potentially get hold of the component that fired the change action. Not in every case you have a similar property like "isSelected" part of the List used in aura:iteration. Sometimes, all you need is Id/index of the records selected rather than storing the appropriate state in the object directly.
    – Praveen
    Commented Apr 20, 2018 at 7:20
2

I've submitted an idea to let us have a global data component, and even tested it in a patched version of Aura. I hope we'll some day have that feature available. For now, consider the slightly less-favorable method of hooking up the event to an element you control:

<aura:iteration items="{!v.categories}" var="category">
    <li data-category-id="{!category.Id}" onchange="{!c.selectCategory}">
       <ui:inputCheckbox value="{!category.isSelected}" />
    </li>
</aura:iteration>

At this point, event.target.dataset.categoryId should be available to you. Also note that in an iterator, do not use "v", which refers to the component's attribute, not the "var" attribute.

You must log in to answer this question.

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