0

I’m working with multiple toggles in a template for bucle and I’m trying to find a way to identify the specific toggle that is enabled/disabled, I can’t use something like this:

this.template.querySelector(“[data-id=value]”)

I tried different things like using the name but apparently nothing works.

Is it possible to identify a toggle in an event handler using a specific property to know which one is enabling/disabling?

enter image description here

2
  • 1
    Can you show some more code? It's kind of hard to work out exactly where you're stuck. For example, do you want this in an event handler on the toggle? Or on a save button? The more details you provide, the better we can help you.
    – sfdcfox
    Jan 9 at 0:06
  • In an event handler, I was looking at the event and target is not returning any information, the detail just the value (checked/unchecked). I can’t show the code because is not of my property. Jan 9 at 1:00
2

I wrote a simple example for you. Without more code to go on, I can't do much more for you, but hopefully this code serves as sufficient demonstration.


import { LightningElement, track } from "lwc";

export default class App extends LightningElement {
  @track features = [
    { key: 1, label: 'Daily Scan', enabled: false },
    { key: 2, label: 'Weekly Scan', enabled: false },
    { key: 3, label: 'Monthly Scan', enabled: false },
    { key: 4, label: 'Yearly Scan', enabled: false }
  ]
  get enabledFeatures() {
    return this.features.filter(item => item.enabled).map(item => item.label).join(', ') || 'None';
  }
  handleToggle(event) {
    this.features.find(item => item.key == event.target.dataset.key).enabled = event.target.checked;
  }
}

<template>
    <lightning-input type="checkbox" label={item.label} data-key={item.key} key={item.key} for:each={features}
        for:item="item" onchange={handleToggle} checked={item.enabled}>
    </lightning-input>
    Enabled Features: {enabledFeatures}
</template>

Demo.

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