Conceal a div depending on the selected radio button within a form

On my form, there are two radio buttons to choose from: one for "yes" and the other for "no". I am looking to create a feature that will hide a specific div on the form when the "no" option is selected. I have tried various JavaScript solutions found online, but none of them seem to work for me.
Can anyone provide the correct code for this functionality? It could be in JavaScript, PHP, or CSS.

Below is the snippet of my current code:

<div class="form-radio">
<label for="sons" class="radio-label">Question:</label>
<div class="form-radio-item">
<input type="radio" name="yes" id="yes" checked value="YES">
<label for="hsi">YES</label>
<span class="check"></span>
</div>
<div class="form-radio-item">
<input type="radio" name="no" id="no" value="NO">
<label for="hno">NO</label>
<span class="check"></span>
</div>
</div>

<div id="hello">
You clicked on NO, so this div disappears.    
</div>

Answer №1

To make your radio button functionality work correctly, ensure that you have event listeners attached to your input elements. Also, remember to assign the same name to both radio buttons. In the code snippet below, I have used inputs as the name for the radio buttons. The display style of the #hello element toggles based on the radio button selection.

const hello = document.getElementById('hello');

document.getElementById('yes')
  .addEventListener('click', function() {
    hello.style.display = null;
  });
  
document.getElementById('no')
  .addEventListener('click', function() {
    hello.style.display = 'none';
  });
<div class="form-radio">
<label for="sons" class="radio-label">Question:</label>
<div class="form-radio-item">
<input type="radio" name="inputs" id="yes" checked value="YES">
<label for="hsi">YES</label>
<span class="check"></span>
</div>
<div class="form-radio-item">
<input type="radio" name="inputs" id="no" value="NO">
<label for="hno">NO</label>
<span class="check"></span>
</div>
</div>

<div id="hello">
You selected NO, and this div will now disappear.    
</div>

Answer №2

To achieve this effect, pure CSS can be used. However, it is important to consider the structure of your entire webpage before implementing any solution.

.form-radio {
  position: relative;
  padding-bottom: 2rem;
}

input#no ~ #floatingDescription  {
  position: absolute;
  bottom: 0px;
  left: 0px;
  display: block;
}

input#no:checked ~ #floatingDescription {
  display: none;
}
<!DOCTYPE html>
<hml>

<body>
  <div class="form-radio">
    <label for="sons" class="radio-label">Question:</label>
    <div class="form-radio-item">
      <input type="radio" name="answer" id="yes" checked>
      <label for="hsi">YES</label>
    </div>
    <div class="form-radio-item">
      <input type="radio" name="answer" id="no">
      <label for="hno">NO</label>
      <div id="floatingDescription">You clicked on NO, so this div disappears.</div>
    </div>
  </div>

</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Selenium 2 to dynamically insert CSS styles into the currently visible webpage

I experimented with using jQuery on a webpage that has already been modified by jQuery in order to add custom CSS code: jQuery('head').append('<style type=\"text/css\">body { background: #000; }</style>'); When I ...

Remove any overlapping datetime values from a JavaScript array of objects

Is there a way to efficiently remove any overlaps between the start and end times (moment.js) in a given array of objects? [{ start: moment("2019-03-23T15:55:00.000"), end: moment("2019-03-23T16:55:00.000")}, { start: moment("2019-03-23T14:40:00.000"), e ...

Struggling with creating a fluid/elastic/liquid layout in HTML. Can someone please assist me with this

I've been attempting to incorporate a fluid layout on my friend's website, but unfortunately, it doesn't seem to be functioning properly. The page is quite simple, with just a slider on it. Could you please take a look at it and let me know ...

Compatibility of HTML5 websites with Internet Explorer

Following a tutorial on HTML5/CSS3, I meticulously followed each step to create a basic website. While the demo of the site worked perfectly in Internet Explorer 8 during the tutorial, my own version did not display correctly when viewed in IE8. I discove ...

concealing components during screen adjustments

There are 3 identical <div>s available: <div class="box">Hello World!</div> <div class="box">Hello World!</div> <div class="box">Hello World!</div> I need these <div>s to ...

Implement Spacing Between Components in React Native

Seeking assistance in resolving the issue of overlapping views within my react native app, specifically requiring spacing between them. Upon clicking the plus sign twice in the top right corner, the two Views overlap without any space between them (referr ...

Validating in Angular cannot be accomplished

I am facing an issue with validating my input against JSON data. Every time I try to compare it with the JSON, only the else block gets executed. Can someone please help me resolve this problem? <body ng-app="fileGetting" ng-controller="loadFile"> ...

What is the reason for using a callback as a condition in the ternary operator for the Material UI Dialog component?

I am in the process of reconstructing the Material UI Customized Dialog component based on the instructions provided in this particular section of the documentation. However, I am unable to grasp the purpose behind using a callback function onClose conditi ...

Is there an issue with the JSON data?

"stocksdata" :[{"id":7,"SCRIP":"ASIANPAINT","LTP":3341,"OHL":"BUY","ORB15":"BREAKOUT","ORB30":"NT","PRB":"NA","CAMARILLA& ...

Decreasing the gap between two <tr> elements

Looking to showcase a company logo alongside the company name without using flexbox for compatibility with older browsers? Take a look at this simple HTML and CSS code snippet: <table style="background-color: cadetblue;width:100%;padding:10px"> ...

Exploring the capabilities of Redux Toolkit's createEntityAdapter in designing versatile data grids

Seeking guidance on utilizing createEntityAdapter from Redux Toolkit. In my application, I display package information and details using the master/detail feature of the AG Grid library. Packages are loaded initially, followed by fetching detailed data as ...

Once all the fields are filled, I would like for my button to trigger the opening of my

I need help figuring out how to summon my modal only when all fields are filled: <form action="" id="myForm"> <fieldset> <input type="hidden" name="action" value="contact_s ...

Unable to obtain the accurate response from a jQuery Ajax request

I'm trying to retrieve a JSON object with a list of picture filenames, but there seems to be an issue. When I use alert(getPicsInFolder("testfolder"));, it returns "error" instead of the expected data. function getPicsInFolder(folder) { return_data ...

Achieving a fixed Bootstrap navbar at the top along with a sidebar: A comprehensive

As I work on developing a webpage that includes both a sidebar and a navbar, it is crucial for me to ensure that the navbar remains fixed at the top for an improved user experience. Problem Statement: However, when I utilize the built-in fixed-top Bootst ...

The view has no access to $scope but the controller does

I need to display the iso code using a $scope when selecting a country from a list. The list of countries is fetched through a $http call in a factory and then stored in a scope. ///////// get countries //////////////// tableFactory.getCountries().then(f ...

After resolving a promise, what is the process for loading a Next.js App?

Seeking guidance on implementing the code snippet below using Next.js. I suspect there is an issue with Next.js not being able to access the window object without being within a useEffect(() => {}) hook. When switching back to regular React, the code ...

When my webpage is opened in Firefox, I notice that it automatically scrolls down upon loading

I recently embarked on the task of building a website from scratch but ran into an unusual bug in Firefox. The issue causes the page to scroll down to the first div, completely bypassing its margin. I want to clarify that I am not seeking a solution spe ...

I'm finding it difficult to understand the reasoning behind the custom hook I created

Looking at the code, my intention is to only execute one of these API requests based on whether origCompId is passed or not. If origCompId is passed as a query parameter, then duplicateInstance should run; otherwise, addNewInstance should be executed. The ...

Tips for building a live React app!

I'm looking to develop a real-time news application that displays a list of countries with the latest news next to each country name, automatically updating as new information is added to the API. For instance, I have an endpoint like this: (for Aust ...

What triggers the appearance of the message "Error: Uncaught (in promise): Response with status:200 for Url:null"?

My current setup involves accessing a Mongo database using NodeJS and Express in the following way: var MongoClient = require('mongodb').MongoClient; ... app.get("/app/visits", function (req, res, next) { console.log(" ...