Sometimes, we want to show div when radio button selected with JavaScript.
In this article, we’ll look at how to show div when radio button selected with JavaScript.
How to show div when radio button selected with JavaScript?
To show div when radio button selected with JavaScript, we can listen to the change event of the radio buttons.
For instance, we write:
<input type='radio' name='foo'>
<input type='radio' name='foo'>
<input type='radio' name='foo'>
<div style='display: none'>
hello
</div>
to add radio buttons and a div that shows when we click on any radio button.
Then we write:
const input = document.querySelectorAll('input')
const div = document.querySelector('div')
for (const i of input) {
i.onchange = () => {
div.style.display = 'block'
}
}
to select all the radio inputs and the div with querySelectorAll
and querySelector
.
Next, we loop through each input and set the onchange
property to a function that’s called when the radio button checked value is changed.
In the function, we set the display
CSS property to block
to show the div.
Conclusion
To show div when radio button selected with JavaScript, we can listen to the change event of the radio buttons.