0

I want a controller logic for aura component so that my lightning:input type="toggle" worked as a radio button.

<aura:component>
    <aura:iteration items="{!v.ebpEmpType}" var="empType">
        <div class="slds-cell-wrap">{!empType.EmpName} </div>
        <input type="hidden" id="{!empType.EmpType}" name="{!empType.EmpName}" class="hidden-emptype-emptypeName"/>
        <lightning:input type="toggle" checked="{!empType.isChecked}" onchange="{!c.addEmpType}" messageToggleActive=""
                         messageToggleInactive=""/>
    </aura:iteration>
</aura:component>
6
  • 1
    Why not use Radio (developer.salesforce.com/docs/component-library/bundle/…) instead? Commented Nov 25, 2020 at 9:06
  • that's the requirement that's why...@NagendraSingh
    – Sagar
    Commented Nov 25, 2020 at 9:11
  • Business requirement is to show a radio button, how to show it, is entirely upto you. Is the business requirement to show a radio button and in the backend it should be a lightning:input field? Commented Nov 25, 2020 at 9:13
  • but is it possible or not that keeping lightning:input toggle and work as a radio button?@NagendraSingh
    – Sagar
    Commented Nov 25, 2020 at 9:18
  • Yes its possible, but again my question is why? What's the use case for this? Commented Nov 25, 2020 at 9:25

1 Answer 1

0

You need to simply look for which toggle is selected and unselect others.

Below is the sample code.

In controller, use event.getSource().get("v.name"); to get the name of the toggle field selected.

Component.html

<aura:component>
  <aura:attribute
    name="selectedButton"
    type="String"
    default=""
  ></aura:attribute>
  <aura:attribute
    name="buttons"
    type="List"
    default="[{'label':'Button1', 'selected': false, 'value':'button1' },{'label':'Button2', 'selected': false, 'value':'button2' },{'label':'Button3', 'selected': false, 'value':'button3' },{'label':'Button4', 'selected': false, 'value':'button4' }]"
  ></aura:attribute>

  <aura:iteration items="{!v.buttons}" var="button">
    {!button.label}
    <lightning:input
      type="toggle"
      checked="{!button.selected}"
      name="{!button.value}"
      onchange="{!c.hangleToggleChange}"
      variant="label-hidden"
      messageToggleActive=""
      messageToggleInactive=""
    />
  </aura:iteration>
</aura:component>

Controller.js

 ({
  hangleToggleChange: function(component, event, helper) {
    var selectedButtonValue = event.getSource().get("v.name");
    component.set("v.selectedButton", selectedButtonValue);
    var buttons = component.get("v.buttons");
    buttons.forEach(function(b) {
      if (b.value === selectedButtonValue) {
        b.selected = true;
      } else {
        b.selected = false;
      }
    });
    component.set("v.buttons", buttons);
  }
});

You must log in to answer this question.

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