Looking for a way to toggle the visibility of multiple Divs based on checkbox status with JQuery?

I'm looking for a way to hide information in a toggle div until a "no" checkbox is clicked. I need a simple jQuery code that can be used for each instance independently, where the divs will only show when a "no" answer is checked. Any help or feedback would be greatly appreciated!

<div>
<ul class="rank">
<li>
    <label>Do you enjoy the color blue?</label>
    <fieldset>
        <label><input  class="no" type="checkbox" /> No</label>
        <label><input  class="yes" type="checkbox" /> Yes</label>
    </fieldset>
    <div class="toggle">
        No, I do not like the color blue!
    </div>
</li>
<li>
    <label>Do you enjoy the color red?</label>
    <fieldset>
        <label><input  class="no" type="checkbox" /> No</label>
        <label><input  class="yes" type="checkbox" /> Yes</label>
    </fieldset>
    <div class="toggle">
        No, I do not like the color red!
    </div>
</li>
<ul>
</div>

<script type="text/javascript">
$(".toggle").hide();
    $(".no").click(function() {
if($(this).is(":checked")) {
    $(".toggle").show(500);
} else {
    $(".toggle").hide(500);
}
});

</script>

Answer №1

Here is the code that should function as intended:

$(".toggle").hide();
$(".no").change(function() {
    $(this).closest('li').find('.toggle').toggle(this.checked);
});

If you desire animation, use this code instead:

$(".toggle").hide();
$(".no").change(function() {
    $((this).closest('li').find('.toggle')[this.checked ? 'show' : 'hide'](500);
});

Update

For better user experience, consider using radio buttons instead of checkboxes for your feature. If you switch to radio buttons, the initial code will need some adjustments.

Check out this revised version:

$(".toggle").hide();
$("input[type=radio]").change(function() {
    var toShow = this.checked && this.value == 'no';
    $(this).closest('li').find('.toggle')[toShow ? 'show' : 'hide'](500);
});

View the demo on Fiddle: http://jsfiddle.net/nrcC4/1/

Additionally, I replaced class="no" with value="no" for improved functionality and clarity.

Answer №2

Reviewing the responses from IT professionals, it appears that the script is too broad in scope. If you select "no", both toggles will be activated.

I have developed a demo on Fiddle to illustrate a specific toggle function.

Note: My recommendation would be to utilize a radio button for a yes/no response or a dropdown menu.

Link to Fiddle Demo

HTML:

<div>
<ul class="rank">
<li>
    <label>Are you fond of the color blue?</label>
    <fieldset>
        <label><input  class="no" type="checkbox" /> No</label>
        <label><input  class="yes" type="checkbox" /> Yes</label>
    </fieldset>
    <div class="toggle">
        No, I do not prefer the color blue!
    </div>
</li>
<li>
    <label>Do you fancy the color red?</label>
    <fieldset>
        <label><input  class="no" type="checkbox" /> No</label>
        <label><input  class="yes" type="checkbox" /> Yes</label>
    </fieldset>
    <div class="toggle">
        No, I am not a fan of the color red!
    </div>
</li>
<ul>
</div>

jQuery:

$(".toggle").hide();
$(".no").click(function() {
if($(this).is(":checked")) {
$(this).parents("li").find('.toggle').show(500);
} else {
$(this).parents("li").find('.toggle').hide(500);
}
});

Answer №3

$('.no').on('click', function() {
   $(this).parent().parent().next('.toggle').fadeToggle(); 
});

.toggle {
    display:none;
}

Link to example in JSFiddle

Answer №5

Here is an innovative approach using delegated events, offering potentially greater dynamism and performance benefits.

$(".toggle").hide();

$(".rank li").on('click', '.no', function(e) {
    if($(this).is(":checked")) {
        $(e.delegateTarget).find(".toggle").show(500);
    } else {
        $(e.delegateTarget).find(".toggle").hide(500);
    }
});

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

Choose ng-change within the table

I've searched everywhere for an answer to this, but I couldn't find it. I have a table that contains select and date input fields. <table id="tblCorrAction" class="table table-bordered table-striped table-hover table-condensed"> <t ...

Tips for arranging three images in a single row

I have 3 payment logos in my footer that I want to center and align in one row. Can someone help me with this? sliki { text-align: justify; } sliki img { display: inline-block; width: 75px; height: 100px; padding: 7px; margin-top: -5px; ...

The initial value for the `useState` is not defined at the

Here's a simplified version of my requirement that demonstrates the issue. The ColorBox component receives a prop called "isVisible" from the ShowColorComponent component, which is used to initially set the state of the ColorBox.visible variable. impo ...

What is the best way to retrieve a value from a multiple select element being utilized by asmselect?

I have a form in my code that I am validating using a JavaScript function called sub(). Once the validation is successful, I am posting the data to a PHP file using $.POST. I am able to fetch the name field using its id, but I am facing issues with fetchin ...

Display current weather conditions with the Open Weather API (featuring weather icons)

Hello everyone, I need some help from the community. I am currently working on a weather app using the openweather API. However, I'm facing an issue with displaying the weather conditions icon for each city. I have stored every icon id in a new array ...

What is the most effective method for dynamically naming a div id and assigning a button data-bs-target using a prop in a Vue.js application with Bootstrap 5?

How to dynamically name a div id and data-bs-target with props in Vue.js I am attempting to assign dynamic identifiers to the id of a div and the data-bs-target of a button using props in order to reuse the same component multiple times on a single page w ...

Tips on extracting a base64 image from a canvas

I have successfully developed a function that is capable of reading an uploaded image and extracting imageData from the canvas. However, I am encountering difficulty in obtaining the base64 image from that imagedata. Here is my code snippet: function han ...

Is there a way to simultaneously send a file and additional information in Flask?

Below is the code I am using to upload a file to Flask. Client Side: <form id="upload-file" method="post" enctype="multipart/form-data"> <fieldset> <label for="file">Select a file</label> <input name="file8" ...

Would this be considered an effective way to utilize JQuery's queues?

Currently, I am working on a webpage that displays a list of users and I need to retrieve icons showing their Skype status from . However, I have encountered issues with the calls to mystatus.skype.com failing when sent simultaneously. To address this pr ...

Reveal or conceal information with a dropdown menu feature

I am attempting to implement a feature where the image file upload section is hidden or displayed based on the selection made in a dropdown list. If the user selects option "2", the image upload section should be hidden. Conversely, if they choose option " ...

Choose either the final choice in the dropdown menu or determine the total number of options available in the dropdown menu when using UI Vision, RPA, Kantu, Selenium

My challenge involves a drop-down menu with changing options. I am looking to dynamically select the last item in this menu, without knowing the total number of items present. I am seeking advice on using xpath for this feature. Specifically, I am using u ...

Build a PHP-driven form for data collection

Previously, I posted this question but didn't receive a clear answer. Here's what I'm confused about: Below is the HTML snippet: <body onload="showcontent()"> <!-- onload optional --> <div id="content"><img src ...

How can one smoothly rewind X frames in a video or animation on a webpage without experiencing lag?

For my thesis presentation, I decided to make it available online as a video with custom controls resembling a powerpoint slideshow. The challenge I encountered was with transitions between slides in an animated video. Certain transitions needed to loop fo ...

The issue with linking to files on a custom 404 error page is that it doesn't function properly when

Having some trouble with my 404 page. I seem to have figured out the issue. The following URL works fine: sia.github.io/404.html and so does this one: sia.github.io/ooofdfsdfaablahblah However, when navigating to sia.github.io/1/2/3/, everything seems to ...

Using AJAX to dynamically edit and update PHP data

The information displayed on my index.php page is fetched from a database using the mysqli_fetch_array function. The data is presented in a table format with fields like Name, Age, Email, and Update. An edit button allows users to modify the data. Here is ...

Does anyone know of a CSS/JavaScript framework that can be used to replicate the look and functionality of the iOS home

I'm wondering if there is a CSS/JavaScript framework that replicates the layout of an iOS home screen. I want to create a kiosk website with a grid layout similar to Android/iOS where apps can be displayed as icons. ...

What is the best way to eliminate the border from a GTK entry (textbox)?

I am trying to remove the border completely. This is the code I have attempted: GtkCssProvider *provider = gtk_css_provider_new (); gtk_css_provider_load_from_data (GTK_CSS_PROVIDER (provider), "entry, .entry, GtkEntry { border-width:0px ; }", -1 ...

Using ngFor to render elements in several table rows

Looking for a solution to display a Python list using Angular in multiple rows instead of a single table row. The current setup is showing more than 200 objects in a single row which is not ideal. List=[1,2,3,4,5, .......100} This is the HTML currently b ...

My goal is to ensure that my website perfectly matches the height of the screen, even though there is not a lot of content

To be more specific, I am looking to have the content section (the section with the white background) fill the remaining space on the page so that the header and footer maintain their fixed sizes while the content section expands to fit the full height of ...

Error: The jQuery Django context dictionary is throwing an error due to an unexpected token "&"

I'm encountering an issue when trying to set a jQuery variable in my Django html template by assigning a context dictionary. The error message appearing in the browser's console reads: Uncaught SyntaxError: Unexpected token & This is how I& ...