Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to control the visibility of a div using radio button selection without using the onclick method in JavaScript is by using the addEventListener() method to attach a listener to each radio button.

Here's an example code:

<!-- HTML -->
<input type="radio" name="visibility" value="visible"> Show
<input type="radio" name="visibility" value="hidden"> Hide

<div id="myDiv">This is the content of the div</div>
// JavaScript
const showRadioButton = document.querySelector('input[value="visible"]');
const hideRadioButton = document.querySelector('input[value="hidden"]');
const myDiv = document.getElementById('myDiv');

showRadioButton.addEventListener('change', function() {
  myDiv.style.display = 'block';
});

hideRadioButton.addEventListener('change', function() {
  myDiv.style.display = 'none';
});

In this code, we first select the radio buttons and the div using their unique IDs and value attributes. Then, we attach a change event listener to each radio button using the addEventListener() method. When the user selects a radio button, it triggers the corresponding event listener function that sets the display property of the div accordingly. If the "Show" radio button is selected, the div is displayed by setting its display property to "block". If the "Hide" radio button is selected, the div is hidden by setting its display property to "none".