First of all I’m new to LWC development so I would like to apologize if the question looks stupid. I’m currently working on a LWC and I would like to create 2 toggles but I want only one toggle to be checked at the same time (same as a radio button group) but I need to have the style of the toggles

enter image description here

I didn’t find an easy way to use radio button and change the css checkbox so I’m using 2 input toggle. The current Idea is to put an Id on the toggle and change their checked/unchecked attributes when any of the other is changed. My problem right now is that I can’t succeed to update any Html attribute from the Javascript controler .

My code is below:

<lightning-input data-id="toggle1" type="toggle" label="TOGGLE1" onchange={changeToggle} unchecked message-toggle-active="" message-toggle-inactive="" ></lightning-input> <br/>
<lightning-input data-id="toggle2" type="toggle" label="TOGGLE2" onchange={changeToggle} unchecked message-toggle-active="" message-toggle-inactive=""></lightning-input> <br/>
changeToggle(event) {
        console.log('event.target: ',event.target);
        console.log('event.target.checked: ',event.target.checked);
        console.log('event.target.label: ',event.target.label);

        const element = this.template.querySelector('[data-id="toggle1"]'); 
        console.log('element: ' , element.checked);
        console.log('element: ' , element.label);
        element.setAttribute('checked', false);
        element.setAttribute('unchecked', true);
        console.log('element: ' , element.checked);


When I have toggle 1 enabled and I enable the second One here is what I see on the log:

enter image description here

Is there another way to update Html Attribute other than set element?


Just bind the checked attribute to javascript property.

<lightning-input data-id="toggle2" type="toggle" label="TOGGLE2" checked={checked} message-toggle-active="" message-toggle-inactive=""></lightning-input> <br/>
<lightning-input data-id="toggle1" type="toggle" label="Click Me" onchange={changeToggle} message-toggle-active="" message-toggle-inactive="" ></lightning-input> <br/>

Update that value from the js method like this.

@track checked = true;
    this.checked = !this.checked;

See the playground

  • 1
    Pretty simple indeed, I was thinking that i couldn't add a value to the checked attribute... Thank you very much! – Julien Souchi Apr 3 '20 at 12:00
  • @Julien Most welcome! – Rahul Gawale Apr 3 '20 at 17:39

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.