1

I have lightning component with below code. I trying change class on aura:id="xcont" when i click a checkbox. background-silver to background-red

<div aura:id="xcont" class="slds-button slds-checkbox--button background-silver">
  <label class="answears slds-checkbox--button__label">
    <ui:inputCheckbox aura:id="x" label="label" click={!c.voidJS}" class="line" />
  </label>
</div>
<div aura:id="xcont" class="slds-button slds-checkbox--button background-silver">
  <label class="answears slds-checkbox--button__label">
    <ui:inputCheckbox aura:id="x" label="label" click={!c.voidJS}" class="line" />
  </label>
</div>

I trying use jQuery for this - this is my function from js controller:

voidJS: function (component, event, helper) {
  var clicked = event.getSource().localId;
  $('#' + clicked).parent().parent().addClass('myclass');
}

css

.THIS .background-silver {
  background: linear-gradient(to bottom, #FAFAFA 0%, #EEEEEE 100%);
}
.THIS .background-red{
  background: linear-gradient(to bottom, #FF7043 0%, #FF5722 100%);
}
4

Since you are rendering the div inside a loop, you should build the inner portion as separate child component and then pass the param as attribute to the child component. In this way, you don't render multiple div and input elements with duplicate aura ids.

OR

as a work around you can do this:

Leverage the labelClass attribute of inputCheckBox, I am assuming you are not using it. The trick is to have the same ID as the div id in the labelClass of inputCheckbox, so that you get its value when the inputcheckbox is clicked, by which you know under which div the input check box was clicked.

<aura:iteration items.... var="obj">
<!-- div is will be like divId006762hdHGtgjHYU -->
<div id="{!'divId'+obj.Id}" class="slds-button slds-checkbox--button background-silver">
  <label class="answears slds-checkbox--button__label">
    <ui:inputCheckbox label="label" click={!c.voidJS}" class="line" labelClass="{!'divId'+obj.Id}"/><!--Use Id or Use any property of obj which is unique. Should be same as div ID -->
  </label>
</div>
</aura:iteration>

I am using Id field of your loop variable, you can use any unique field value.

Next in your voidJS method,

var clickedElement = event.getSource().get('v.labelClass');
$('#' + clickedElement).removeClass('background-silver');
$('#' + clickedElement).addClass('background-red');

Again, this might not be the most appropriate way of doing this but it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.