ArticleZip > Show Div When Radio Button Selected

Show Div When Radio Button Selected

So you're working on a project or a website and you want to display a specific section only when a particular radio button is selected? I've got you covered! In this guide, I'll walk you through how to achieve this functionality using HTML, CSS, and JavaScript. Let's dive in.

First things first, let's set up our HTML structure. You'll need a group of radio buttons and a corresponding div that you want to show when a specific radio button is selected. Here's a simple example to get you started:

Html

<label for="option1">Option 1</label>


<label for="option2">Option 2</label>

<div id="hiddenDiv">
    This is the content you want to show when a radio button is selected!
</div>

In the above snippet, we have two radio buttons with unique IDs, 'option1' and 'option2'. We've also included a hidden div with the content that we want to display when a radio button is selected. By default, the div is hidden using CSS `display: none`.

Now, let's add some JavaScript to show or hide the div based on the selected radio button.

Javascript

function showHideDiv() {
    var option1 = document.getElementById("option1");
    var hiddenDiv = document.getElementById("hiddenDiv");

    if (option1.checked) {
        hiddenDiv.style.display = "block";
    } else {
        hiddenDiv.style.display = "none";
    }
}

In the `showHideDiv` function, we first retrieve the radio button element and the hidden div element by their IDs. We then check if the 'option1' radio button is checked. If it is, we display the hidden div by setting its `display` property to `'block'`, making it visible. If the radio button is not checked, we hide the div by setting its `display` property back to `'none'`.

You can extend this functionality by adding more radio buttons and corresponding hidden divs. Simply adjust the IDs and logic in the JavaScript function accordingly.

And there you have it! You've successfully implemented a feature to show a div when a radio button is selected on your webpage. Feel free to customize the styles and content to suit your project requirements.

Hope this guide was helpful in achieving the functionality you were looking for. Happy coding!

×