0

This is the code

I have a group of hidden radio inputs with the same name

    <input name="megamenu" type="radio" id="menu-1" hidden>
    <label class="nav-link" for="menu-1">menu1</label>
    
    <input name="megamenu" type="radio" id="menu-2" hidden>
    <label class="nav-link" for="menu-2">menu2</label>
    
    <input name="megamenu" type="radio" id="menu-3" hidden>
    <label class="nav-link" for="menu-3">menu3</label>

When I click on each label they get checked. How can I uncheck a checked radio input by click on its label?

My attempt

    if (document.querySelector('input[name="megamenu"]:checked')) {
      document.querySelectorAll('input[name="megamenu"]:checked').forEach((elem) => {
        elem.addEventListener("click", function(event) {
    
          event.target.checked = false;
    
        });
      });
    }

I also tried this

    var radios = document.querySelectorAll('input[name="megamenu"]:checked');
    for(i=0; i<radios.length; i++ ) {
        radios[i].onclick = function(e) {
            if(e.ctrlKey || e.metaKey) {
                this.checked = false;
            }
        }
    }
Gass
  • 7,536
  • 3
  • 37
  • 41
Ali
  • 1,127
  • 1
  • 10
  • 23

1 Answers1

0

An easy way to do this is by using the .checked JS property, like in the following snippet:

let label = document.getElementById('label-id');
let radioBTN = document.getElementById('radio-id');

label.addEventListener('click', function(){ radioBTN.checked = false })
<input id='radio-id' type='radio' checked/>  <br><br>

<label id="label-id" style='cursor:pointer'>
  Click this label to uncheck the radio button
</label>

For more info click here

Gass
  • 7,536
  • 3
  • 37
  • 41