Show secret information once radio button is selected through JQuery code

I am dealing with two checkboxes

ABC
XYZ

When the ABC checkbox is checked, the abc content div is displayed, and when the XYZ checkbox is checked, the xyz content div is shown.

Everything works fine, except that if the ABC checkbox is checked by default, the abc content div is not displayed until clicked.

My goal is to have the hidden content of the checked radio button displayed when the radio button is checked, not just on click.

Can anyone assist me in accomplishing this?

http://jsfiddle.net/Qac6J/497/

HTML

<form id='group'>
    <div>

        <label>
            <input type="radio" name="group1" class="trigger" data-rel="abc" checked />ABC
        </label>

        <span class="abc content">
            <label>
                <span>I belong to ABC</span>
                <input type="button" value="ABC"/>
            </label>
        </span>

    </div>
    <br>
    <div>

        <label>
            <input type="radio" name="group1" class="trigger" data-rel="xyz"/>XYZ
        </label>

        <span class="xyz content">
            <label>
                <span>I belong to XYZ</span>
                <input type="button" value="XYZ"/>
            </label>
        </span>

    </div>
</form>

CSS

.content
{
    display: none;
}

JQuery

$('.trigger').change(function() 
{
    $('.content').hide();
    $('.' + $(this).data('rel')).show();
});

Answer №1

To retrieve the value of the checked radio button, you can utilize the rel attribute and apply the :checked selector

$('.trigger').change(function () {
    $('.content').hide();
    $('.' + $('.trigger:checked').data('rel')).show();
}).change(); //Display content when the page loads

Fiddle

Thank you @tushar. By restructuring the layout, you can achieve this using only CSS.

You can employ :checked to target the checked radio button and the sibling selector + to select the next span and input siblings, then apply display: block; to display them.

.content {
  display: none;
}
input:checked + span,
input:checked + input {
  display: block;
}
<form id='group'>
  <div>
    <label>
      <input type="radio" name="group1" class="trigger" data-rel="abc" checked />ABC
      <span class="abc content">
        <span>I belong to ABC</span>
      <input type="button" value="ABC" />
      </span>
    </label>
  </div>
  <br>
  <div>
    <label>
      <input type="radio" name="group1" class="trigger" data-rel="xyz" />XYZ
      <span class="xyz content">
        <span>I belong to XYZ</span>
      <input type="button" value="XYZ" />
      </span>
    </label>
  </div>
</form>

Answer №2

To fix the issue, simply delete the line of code that says .change(); in your JavaScript file.

$('.trigger').change(function () {
    $('.content').hide();
    $('.' + $('.trigger:checked').data('rel')).show();
});

Check out the updated Fiddle here

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

Trick for hiding CSS elements when input field is vacant

Is there a way to hide the search result when the input is empty? While everything is functioning correctly, I would like to prevent the search result from remaining visible after clearing the input field. For example, if you type 'A' and then d ...

What is the method for deactivating a hyperlink with CSS?

Within my wordpress page, there is a specific link present. This particular link belongs to a class. Is it viable to deactivate this link solely through the use of CSS? <a class="select-slot__serviceStaffOrLocationButton___5GUjl"><i class="mater ...

Tips for ensuring that all children within a flex-container have equal heights

I seem to be facing an issue with this problem. My goal is to ensure that all the child divs within a flex container have the same height as the tallest child div, which in this case is 100px. Additionally, I want them to be aligned at the center. I&apos ...

Storing autocomplete JSON responses for faster retrieval

Is there a way to optimize browser caching for JSON API responses in scenarios like autocomplete? We have a form where users input building names With approximately 1500 building names, we want to avoid unnecessary downloads Our API query is triggered af ...

How to Prevent Annoying Flickering of Jquery toggle() in Safari

Having some issues with a basic toggle effect in Safari. There's an irritating flicker at the end of the hide animation. Any suggestions? CSS #menu { position:absolute; left: 30px; top: 30px; padding: 30px; background: #FF0; } # ...

Can the tooltip of an element be changed while the old tooltip is still visible without having to move the mouse away and then back again?

When I have an HTML anchor element with a tooltip that appears when the mouse is hovered over it, and then I use JavaScript to change the tooltip's text using element.title = "Another Tooltip", the new tooltip text does not immediately update visually ...

Why is it that every time I press the play button, nothing happens?

When I try to click on the play button, it does not start playing. I suspect there is something that needs to be adjusted in the javascript. Can someone please assist me in fixing this issue? Link to the example View Screenshot <script> (functio ...

When hovering on the list items, the text-decoration with a border-bottom and vertically centered unordered list "jumps"

I'm specifically looking for a solution using CSS only. I have a navigation bar with an unordered list containing list items. My question is how to underline these list items with a border-bottom. The additional requirement is that the navigation bar ...

Tips for adjusting font sizes within the same HTML header?

Looking to design an HTML header in the following format: "(10.3.4) Version1: vs (10.3.4) Version2:" Need the version numbers to be smaller than "Version1" and "Version2." Any ideas on how to achieve this? ...

What impact does the website logo have on a webpage?

Recently, I made the decision to stop using "img" tags for the logo on my webpage. While the logo serves as a design element rather than actual content, I still wanted to maintain control over its appearance. Instead, I opted to display the logo title with ...

How to Customize the Menu Style in Your WordPress Theme

As a newcomer to Wordpress theme development, I am struggling to properly style my navigation menu. Below is the raw HTML code I have: <!-- Navigation --> <nav class="navbar navbar-default navbar-custom navbar-fixed-top"> <div cl ...

Aligning a row with space between columns

I am looking to display 6 divs on my website with a margin between them for aesthetics. In order to maintain the design when resizing the site, I had to specify widths for the columns. However, I am struggling to center all the cols effectively, despite tr ...

Incorporating @font-face webfonts into a Jekyll project

I'm currently working on incorporating webfonts into a Jekyll build. Interestingly enough, the fonts show up perfectly fine when I view them locally, but once I push my project to a live environment, the fonts mysteriously disappear. To make matters w ...

Implementing class styles using jQuery; however, certain styles fail to be effectively applied

As a beginner, I am experimenting with applying CSS class styles using jQuery. Specifically, I am trying to set two class attributes: color and font size. Surprisingly, only the color attribute is being applied despite both attributes being defined under t ...

What could be causing jQuery document ready to restrict access to global variables?

Currently, I am working on a project that involves three separate JavaScript files (example1.js, example2.js, and example3.js) being scripted into a single HTML file (index.html). These JS files are responsible for making an API call and manipulating the r ...

Storing user-provided image files in Laravel: A comprehensive guide

I am facing an issue with a file insert box in my HTML file. The code looks like this: <input id="image" type="file" name="image" value="{{ old('image') }}" accept="image/gif, image/jpeg, image/png& ...

"Efficiently Switching Between div Elements: A Guide to Toggling Content

I am looking to use two separate divs to toggle my content. By clicking on the "open" div, the contents will open, and by clicking on the "close" div, the contents will close. <div class="open"></div> <div class="close"></div> < ...

Ways to adjust .keyup based on the presence of a variable

I am currently in the process of constructing a search form that utilizes an ajax function within .keyup, which may have various arguments. I aim to determine if a specific argument should be included based on the presence of another value. Here is my curr ...

Incompatibility issues between jQuery and Mozilla Firefox

I have encountered a strange issue while using a simple piece of code. $("container").load(url, function(){ callback();}) With this code, I am able to replace the content of a div container using jQuery's AJAX functionality. It works perfectly fine ...

Having trouble displaying JSON response in Firefox console with Django

Code Snippet: from .views import get_data app_name = 'javascript' urlpatterns = [ path('', views.index, name='index'), path('api/data', get_data, name='api-data'), ] Views.py: from django.http ...