Radio buttons + checkbox (stackoverflow)

by rhelminen

HTML

<div id="radios">
  <div>
    <input type="radio" id="radio1">
    <label for="radio1">Option 1</label>
  </div>
  <div>
    <input type="radio" id="radio2">
    <label for="radio2">Option 2</label>
  </div>
  <div>
    <input type="radio" id="radio3">
    <label for="radio3">Option 3</label>
  </div>
</div>

<div>
  <input type="checkbox" id="check">
  <label for="check">Remove all question from UI</label>
</div>

JavaScript

const radiosWrapper = document.querySelector('#radios')
const radios = document.querySelectorAll('input[type="radio"]')
const checkbox = document.querySelector('input[type="checkbox"]')

// Give the same name to all radio buttons for proper radio button functionality
// Listening to 'change' events is often better than clicks, since they will also trigger when clicking on the label
radios.forEach(radio => {
  radio.name = 'my-radio-button'
  radio.addEventListener('change', () => checkbox.checked = false)
})

checkbox.addEventListener('change', () => {
  const selectedRadio = [...radios].find(radio => radio.checked)
  
  // Clear radio button selection
  if (selectedRadio) selectedRadio.checked = false
  
  // Hide/show radio buttons
  radiosWrapper.toggleAttribute('hidden')
})