0

I currently have an accordion which is done by checked and unchecked radio buttons. When the page is loaded everything is collapsed however I have no way to achieve this after they have initially been opened. I want to be able to fully collapse the accordion again. https://codepen.io/anon/pen/WMdQdv

input[type=radio] + label::after {
 content: "\25BC";
 }
fraser dale
  • 1,187
  • 1
  • 9
  • 18

3 Answers3

4

You should use a checkbox instead:

<input id="tab-four" type="checkbox" name="tabs2">

Updated codepen.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
  • It sounds like to me the OP wants something that will close when a different option is selected, a checkbox won't do that (without js). – Get Off My Lawn Feb 16 '18 at 22:29
0

As Michal's answer says, you should use a checkbox instead of a radio button.

For the reason why:

Radio buttons can't be unchecked. Once you select one, you can change which one is selected, but you can't manually uncheck it.

Checkboxes, on the other hand, are a toggle. So they'll work better in your situation.

Lee A.
  • 33
  • 6
0

You can add a click event listener to the labels, check if the corresponding input is currently checked, and if so, uncheck it by setting its checked property to false. You also have to call event.preventDefault() to prevent it from being checked again.

document.querySelectorAll('label').forEach(el =>
  el.addEventListener('click', (event) => {
    const inputId = event.target.getAttribute('for');
    const input = document.getElementById(inputId);
    if (input.checked) {
      input.checked = false;
      event.preventDefault();
    }
  })
);

Updated codepen.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177