Hiding divs toggle off when either all or only one is selected

In a certain page, there is a script that displays a div when a user selects an option. The script functions correctly, except for a scenario where if the user selects 'd' (which shows 'a', 'b', and 'c'), and then selects another option like 'a', it hides 'a' but keeps 'b' and 'c' visible. The issue arises when the user selects 'c' and then 'a', as the script should not hide 'a' in this case.

Below is the script code. The divs are identified by ids "one box", "two box", and "three box." To view the script fiddle, click here: https://jsfiddle.net/bcLuo0bg/8/. You can also check out a live version of the script here:

<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
    if($(this).attr("id")=="a"){
        $(".one").toggle();
    }
    if($(this).attr("id")=="b"){
        $(".two").toggle();
    }
    if($(this).attr("id")=="c"){
        $(".three").toggle();
    }
     if($(this).attr("id")=="d"){
        $(".box").toggle();
    } 

});
});
</script>

Answer №1

One effective method is to first conceal everything before executing your desired action

$('input[type="checkbox"]').click(function(){
    $(".box").hide();
    if($(this).attr("id")=="a"){
        $(".one").toggle();
    }
    if($(this).attr("id")=="b"){
        $(".two").toggle();
    }
    if($(this).attr("id")=="c"){
        $(".three").toggle();
    }
     if($(this).attr("id")=="d"){
        $(".box").toggle();
    } 

});

Answer №2

To initially hide all the divs, I suggest placing $(".box").hide(); outside the onclick function in your code.

Answer №3

For optimal efficiency, include .box { display: none; } in your CSS stylesheet instead of relying on jQuery or JavaScript to hide elements. By placing this code in the CSS file, it loads sooner and allows for quicker rendering compared to waiting for DOM loading with jQuery or JavaScript.

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

What is the best way to save items for later use with the .not() method?

Is there a way to combine $( "#c1" ).parents() with the .not() function successfully? I considered saving the selector in a variable, for example: var ele = $( "#c1" ).parents(); However, I wasn't sure about the next steps or how to proceed. ...

Chrome method for creating Flexbox columns of equal height

I am implementing a simple 2-column layout and I want to utilize Flexbox to ensure equal heights for the columns: HTML <div class="row flex"> <!-- menu --> <div class="col-xs-4"> <aside> Menu content wi ...

Having trouble transmitting data with axios between React frontend and Node.js backend

My current challenge involves using axios to communicate with the back-end. The code structure seems to be causing an issue because when I attempt to access req.body in the back-end, it returns undefined. Here is a snippet of my front-end code: const respo ...

Responsive height using Material Design Lite

I have a website using MDL, with a prominent header centered on the page. To enhance visibility, I added a background box behind the text. To view the CodePen example, click here. The challenge is to ensure that when the window is resized, such as on a m ...

Vue.js error: Trying to access an undefined property

Here is my Vue instance setup: const vueApp = new Vue({ el: '#vue-wrapper', data: { items: [] }}); Utilizing a v-for loop in index.html.eex: <div v-for="item in items[0].subItems">{{ item.name }}</div> In this scri ...

Using Angular 8, remember to not only create a model but also to properly set it

hello Here is a sample of the model I am working with: export interface SiteSetting { postSetting: PostSetting; } export interface PostSetting { showDataRecordAfterSomeDay: number; } I am trying to populate this model in a component and set it ...

Having trouble getting the `transformItems` feature in React InstantSearch RefinementList to

I recently integrated the React InstantSearch library into my app and I'm working on customizing the refinement list to display only relevant filters for the active user. I attempted the following code: <RefinementList attributeName="organization" ...

When coding in JavaScript, the value of "this" becomes undefined within a class function

I'm facing an issue with my TypeScript class that contains all my Express page functions. When I try to access the class member variable using this, I get an 'undefined' error: class CPages { private Version: string; constructor(ver ...

Having trouble with Angular JS functionality

Today is my first day diving into AngularJS and I'm eager to learn more! Despite grasping the concept of how model-controller-views operate in AngularJS, I encountered an issue where the variables are not displaying as expected. Instead of the values, ...

Tips for saving data obtained from an ajax call

My jquery ajax function has a callback that creates an array from retrieved json data. Here's an example: success: function (response) { callback(response); }, The callback function, in this case createQuestionsArray(), populates ...

Angular2 data binding does not update when properties change

I'm struggling to establish the connection between the fields and the component in order for them to update when the properties change in OnDataUpdate(). The field "OtherValue" successfully binds two ways with the input field, and the "Name" field di ...

An original phrase hidden within the Python3 source code of an HTML webpage

Seeking guidance on extracting specific text from an HTML document using Python3. One example involves utilizing the search engine . The goal is to perform a key search for var error=document.getElementById; and display the content within the parentheses, ...

Turn a textfield on and off in real-time

Hey everyone, I've been working on making a textfield dynamic and I wanted to share my code with you: <input type="text" id="test1" value ="dynamic" onfocus="this.disabled=true" onblur="this.disabled=false"> <input type="text" id="test2 ...

How to stop an AJAX request using Chrome developer tools?

Is there a way to cancel an initiated ajax request from Chrome Developer Tools? I want to test if my fallback message displays correctly without changing the code. Setting No throttling to Offline will make all calls fail, but I just need one API to fail f ...

Searching for the position of objects within a collection?

I am seeking the ability to parse through an object and allocate each of its available attributes to a variable. Within this scenario, there are four potential properties present in different objects - some containing all four while others may only have t ...

What is the best way to reset the 'aria-expanded' attribute to 'false' as I navigate to the following element?

My menu has 2 dropdown buttons, each with a default 'aria-expanded'=false value. The buttons also have the 'up' and 'down' classes to indicate when they are expanded or closed. The issue arises when I click on the first button ...

The definition of require is missing in the MEAN stack node

Currently experimenting with building an application on the MEAN stack and encountered a hurdle involving the use of Node's require function. Here is my current project structure: -- app -- images -- scripts -- app.js // configuration fi ...

What is the best way to overlay several hidden links on a single image using HTML?

Currently working on a project using Flask and I am interested in creating an interactive image where clicking on different sections will navigate to unique links. Is this achievable? Any guidance or resources on how to implement this feature would be mu ...

Using JavaScript, what is the method for inputting values into a window.prompt()?

I've been working on a project that involves scraping basic HTML pages from an internal server at my workplace. When I visit these pages, a popup window similar to a windows.prompt() appears, asking for a username and password with the message "Enter ...

"Efficient Ways to Manage Various File Types in React: xlsx, pptx, doc, docx

I am encountering an issue with downloading files in my React application. The API is functioning properly as confirmed using Postman, where different file formats such as xlsx, pptx, doc, docx, ppt and xls can be downloaded and opened successfully. Howev ...