A guide on displaying containers with jQuery and CSS

Looking to create a smiley survey using only Front-End technologies.

Once a radio button is selected, the associated content should appear for comments. Currently, I have set up my CSS with display: none.

I attempted to implement this functionality using jQuery but haven't had success so far.

Appreciate any advice or suggestions you may have!

$("input[type='radio']").change(function(event) {
  var id = $(this).data('id');
  $('#' + id).addClass('face-cc').siblings().removeClass('none');
});
<div class="cc-selector row" id="moods">
  <div class="col">
    <input type="radio" type="radio" name="smile" value="angry" />
    <label class="face-cc" for="angry">
       <span class="far fa-angry" aria-hidden="div"></span>
     </label>
    <p>Terrible</p>
  </div>

  <div class="col">
    <input type="radio" name="smile" value="grin-stars"/>
    <label class="face-cc" for="grin-stars">
      <span class="far fa-grin-stars" aria-hidden="div"></span>
    </label>
    <p>Excellent</p>
  </div>
</div>

<div class="none" id="text">
  <div class="container">
    <form action="/action_page.php">
      <div class="row p-5">
        <div class="col-sm-12">
          <div class="form-group shadow-textarea">
            <label for="feedback">If you have any additional feedback, 
               please let us know below...
            </label>
            <textarea class="form-control p-2" id="comment" rows="7" 
              cols="20" placeholder="Comment here...">
            </textarea>
          </div>
          <button type="submit" class="btn btn-danger">
            Submit
          </button>
        </div>
      </div>
    </form>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
</script>

Answer №1

Your approach has a few flaws that need addressing. Firstly, it is important to assign id attributes to the radio buttons in your HTML for easier identification of individual click events and value inspection. I have added some id's based on the existing name attribute of the radio buttons.

Secondly, I completely revamped the jQuery code to align with the addition of id attributes. This modification ensures that when a radio button is clicked, the script checks if its id matches the specified one, and then displays the corresponding element accordingly.

Show/hide functionality can also be achieved through CSS. Although I removed the display: none; CSS class for the above changes to take effect, you can retain it and utilize jQuery's toggleClass, addClass, and removeClass methods based on the implemented logic.

I simplified the logic further by incorporating a ternary operator, which provides a more concise syntax.

Last but not least, a quick search on platforms like StackOverflow can offer valuable insights. In fact, I came across an answer on StackOverflow (link) that precisely addresses the jQuery issue in your code. I took the time to explain my approach comprehensively because adjustments in both HTML and CSS were necessary in your case.

If you found this solution helpful, please consider 'accepting' or 'upvoting' it. Welcome to the Stack Overflow community!

var text = $('#text');
var showId = 'grin-stars';

$('input[type="radio"]').click(function() {
  $(this).attr('id') === showId ? text.show() : text.hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cc-selector row" id="moods">
  <div class="col">
    <input id="angry" type="radio" name="radioBtn" value="angry" />
    <label class="face-cc" for="angry">
       <span class="far fa-angry" aria-hidden="div"></span>
     </label>
    <p>Terrible</p>
  </div>

  <div class="col">
    <input id="grin-stars" type="radio" name="radioBtn" value="grin-stars"/>
    <label class="face-cc" for="grin-stars">
      <span class="far fa-grin-stars" aria-hidden="div"></span>
    </label>
    <p>Excellent</p>
  </div>
</div>

<div id="text">
  <div class="container">
    <form action="/action_page.php">
      <div class="row p-5">
        <div class="col-sm-12">
          <div class="form-group shadow-textarea">
            <label for="feedback">
               If you have any additional feedback, please let us know below...
            </label>
            <textarea class="form-control p-2" id="comment" rows="7" 
              cols="20" placeholder="Comment here...">
            </textarea>
          </div>
          <button type="submit" class="btn btn-danger">
            Submit
          </button>
        </div>
      </div>
    </form>
  </div>
</div>

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

Having a problem with Node.js and async.eachSeries? Want to figure out how to configure the callback function to generate a JSON file for each element in an array of

Currently, I am utilizing async.eachSeries to repeatedly call a function that generates an array called pointsForFormating. Each time this function is called, I format the pointsForFormating array and store the result in another array named pointsFormate ...

Having trouble accessing a website that is embedded within an iframe, and experiencing issues with several ajax post requests not functioning properly within the iframe specifically on Chrome

I am currently dealing with a situation where I have two distinct websites, (constructed with PHP) and (also a PHP site). To integrate them, I have embedded site1 inside site2 using an iframe. <iframe src="https://site1.com" seamless width= ...

Hide the overlay fullscreen menu upon clicking an anchor link

I'm having trouble with Javascript, but some of you might find this easy. I found a fullscreen overlay menu on Codepen and I'm trying to figure out how to close it when clicking an anchor link. Looking for assistance with adding javascript to c ...

NodeJS reference copying problem

After encountering an issue where changes to the original object were being reflected in a copy due to JavaScript referencing, I followed recommendations and updated my code as follows: const originalData = {...docid[0][0].Record} // or const originalData ...

What's the reason for this Ajax request taking such a long time to display on the

My webpage features dynamic content created by Ajax, refreshing every 30 seconds with new information from the database. The PHP side of things seems to be functioning properly, but I suspect there might be an issue either in my JavaScript code or within t ...

Issue with Google map displaying incorrectly when attempting to print

I am experiencing an issue with printing a Google Map using the JavaScript API V3. The problem I am facing is that the map is split into two parts, with the top and bottom sections overlapping each other. Here is the code snippet: var geocoder; var ...

Establishing header cache control within the KOA framework

I'm currently working on an app that is using the KOA framework, and I am struggling to understand why a specific page is being cached. Even after attempting a hard reload in all browsers, the changes do not appear unless the cache is cleared. I woul ...

What is the best way to implement a delay for ajax requests triggered by onkeyup events, and then restart the delay countdown each

Is there a way to add a delay for ajax requests triggered by onkeyup and reset the delay if onkeyup is triggered again? For instance, consider this code: When a user enters data into id="fname" triggering an onkeyup event, a loading span id="loading" wil ...

How to customize the color of radio buttons in JFXRadioButton using CSS

I am facing an issue with customizing the styling of JFXRadioButton component from this library : jfoenix.com I want to modify the color of the circle, but the default class is not working. Are there any suggestions or solutions available? (The colors me ...

Can you tell me the Bootstrap 4 equivalent class for '.well'?

While using bootstrap-3, the .well class can be utilized to create a rounded border around an element with a gray background color and padding. <div class="well">Basic Well</div> However, it seems that there is no .well class available in boo ...

Why does the getComputedStyle function return null for IE11 and Edge when using Kendo React Grid within a Popout window, while it works fine in Chrome, Opera, and Firefox?

Check out my stackblitz demo where I am experimenting with rendering a Kendo React Grid inside a popout window using the react-popout-component. The demo runs smoothly in Chrome, Opera, and Firefox, but encounters issues in Edge and IE11 due to a null valu ...

Looping through nested arrays in an array of objects with Angular's ng-repeat

I'm struggling to access an array within an array of objects in my AngularJS project. Here's the HTML: <li ng-repeat="ai in main.a2"> <div np-repeat="bi in ai.b"> <span ng-bind="bi"></span>b2 </div> </l ...

Steps for positioning a z-indexed division

In my main wrapper, which has a fixed width of 960px, there is a login button located at the top right corner. When this button is pressed, a div layer opens directly below and in front of the main wrapper using z-index: 1. The issue I am facing is that I ...

Is there a way to incorporate a click function into this code if the id and xpath methods are ineffective?

Check out the code snippet below: <div class="btn-group" style="margin-top: -10px; box-shadow: none !important;"> <a class="btn btn-clear store-name headerActive" style="margin-left: 0px !important;" ng-click="account();" _href="#/app ...

Perform Function Again

Recently, I came across some code for a tesseract ocr from Google that seemed to be functioning well. However, I encountered an issue where it would work fine the first time I input a URL, but on the second run, it wouldn't work without a manual page ...

Inserting a crisp white divider between items in breadcrumb navigation in the form of arrowheads

I have designed a unique custom breadcrumb with an arrow shape : <ol class="breadcrumb-arrow"> <li class="active"><a href="#">1. Foo<span class="arrow"></span></a> </li> <li ...

locate an inner div element

Here are two div elements: <body> <div id="divParent"> <div id="divChild"></div> </div> </body> What is the best way to select the divChild element using JavaScript? ...

What is the best way to position an image beside a jquery dialog box?

Apologies for not finding a suitable topic to discuss. Is it possible to place an image next to a jQuery dialog, similar to the following example? If so, how can this be achieved? ...

What is the best way to horizontally align an element within a Material UI Grid item?

How do I align elements in the center of a Material UI Grid item? Check out this code snippet from my React project: <Grid container> <Grid item xs={4}> // Other content goes here </Grid> <Grid item xs={4}> // How can ...

The struggle of accessing child components using ViewChild in Angular

I am facing an issue with a dialog box that is supposed to display a child component separately. Below is the code for the child component: @Component({ selector: 'userEdit', templateUrl: './edituser.component.html', styleUrls: [ ...