muestra un elemento html oculto al seleccionar un button radio in javascript

To show a hidden HTML element upon selecting a radio button, you can use JavaScript to add an event listener to the radio buttons and modify the CSS "display" property of the target element.

First, give your target HTML element an ID so that it can be easily targeted with JavaScript:

<div id="hidden-element" style="display: none;">
  This element is hidden by default.
</div>
93 chars
4 lines

Then, create your radio buttons and assign them the same name attribute. This ensures that only one radio button can be selected at a time:

<label>
  <input type="radio" name="show-element"> Show element
</label>
<label>
  <input type="radio" name="show-element"> Hide element
</label>
146 chars
7 lines

Next, use JavaScript to add an event listener to the radio buttons. Inside the event listener function, target the element with the designated ID and modify its "display" property based on the selected radio button:

const showElementRadio = document.querySelectorAll('input[name="show-element"]');

showElementRadio.forEach((radio) => {
  radio.addEventListener('change', () => {
    const hiddenElement = document.getElementById('hidden-element');
    if (radio.value === "Show element") {
      hiddenElement.style.display = 'block';
    } else {
      hiddenElement.style.display = 'none';
    }
  });
});
393 chars
13 lines

In the example above, the "hidden-element" is initially set to "display: none" in the HTML. When the radio button named "Show element" is selected, the "hidden-element" is set to "display: block", thus showing the element. Conversely, when the radio button named "Hide element" is selected, the "hidden-element" is set to "display: none", thus hiding the element again.

gistlibby LogSnag