Ask Your Question
0

How can radio button selection be used to control the visibility of a div using JavaScript without using the onclick method?

asked 2023-07-10 09:26:55 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-10 09:29:01 +0000

qstack gravatar image

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".

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-10 09:26:55 +0000

Seen: 10 times

Last updated: Jul 10 '23