What is the best way to display one div based on two radio button selections using jQuery?

I am currently facing a development challenge with my jQuery script. Despite searching for solutions to repurpose, I have been unable to find exactly what I need. I attempted to write my own solution, but as a novice, I am struggling to get it to function correctly.

My goal is to have 2 sets of radio buttons (3 in the first group, 2 in the second) that will display one of six div tags based on the selection of both groups of radio buttons.

Currently, I have only written enough script for the clinical options - either sales or support.

For the HTML code:

<div class="input-quest">Question 1</div>
<div id="optSelectBU">
    <input type="radio" name="button1" value="clinical" />
    <label>Clinical</label>
    <input type="radio" name="button1" value="financial" />
    <label>Financial</label>
    <input type="radio" name="button1" value="pharmacy" />
    <label>Pharmacy</label>
</div>
<div class="input-quest">Question 2</div>
<div id="optSelectService">
    <input type="radio" name="button2" value="support" />
    <label>Support</label>
    <input type="radio" name="button2" value="sales" />
    <label>Sales</label>
</div>
<div id="Clinical-Support">
    <div class="block">
        <div class="input-quest">Div 1</div>
    </div>
</div>
...

As for the script:

$(document).ready(function () {
    // Initial hide
    $("#Clinical-Support").hide();
    ...

    // Change event handlers
    $("#optSelectBU").change(function () {
        if ($('input[name=button1]').val() == "clinical" && $('input[name=button2]').val() == "sales") {
            ...
        } else {
            ...
        }
    });
    
    $("#optSelectBU").change(function () {
        if ($('input[name=button1]').val() == "clinical" && $('input[name=button2]').val() == "support") {
            ...
        } else {
            ...
        }
    });
});

You can also view the fiddle link: http://jsfiddle.net/schoward30506/LV5nQ/3/

Answer №1

Although it may not be the most visually appealing solution, utilizing data-attributes instead of id can greatly simplify your code:

$(document).ready(function () {    
    $("div[data-cats]").hide();    
    $("input[name=button1], input[name=button2]").change(function () {
        var b1 = $('input[name=button1]:checked').val();
        var b2 = $('input[name=button2]:checked').val();
        $("div[data-cats]").hide();        
        $("div[data-cats='"+b1+" "+b2+"']").show();       
    });
});

http://jsfiddle.net/LV5nQ/6/

Answer №2

After experimenting with different options, I was able to devise a solution for the problem at hand. It's worth noting that I included a div#container to encapsulate the changing div elements.

Check out my solution on jsFiddle

$(document).ready(function () {
    $("#container > div").hide();

    var input1, input2;

    function checkboxVerifier() {
        if (input1 === "clinical" && input2 === "sales") {
            $("#Clinical-Sales").show().siblings("div").hide();
        } else if (input1 === "clinical" && input2 === "support") {
            $("#Clinical-Support").show().siblings("div").hide();
        } else {
            $("#container > div").hide();
        }
    };

    $("input[name=button1], input[name=button2]").change(function () {
        input1 = $('input[name=button1]:checked').val();
        input2 = $('input[name=button2]:checked').val();
        checkboxVerifier();
    });
});

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

Unable to expand Bootstrap navbar due to collapsing issue

I recently implemented a collapsed navbar on my website using bootstrap. However, I'm facing an issue where it does not open when clicking on the hamburger menu. After researching various solutions for this problem and trying them out, none of them s ...

Troubleshooting IE Freezing Issue Due to JavaScript Code with .addClass and .removeClass

Need some help troubleshooting why my code is causing IE to crash. After commenting out sections, I discovered that the issue arises when using .addClass and/or .removeClass inside the if conditions: if ( percentExpenses > 50 && percentExpenses ...

Centralizing images in a Facebook gallery/lightbox during the loading process

Is the image width and height stored in Facebook's gallery database? In typical JavaScript usage, the image width and height cannot be determined until the image is fully loaded. However, on Facebook, images are pre-loaded before being displayed, ens ...

Using JQuery to specifically include only the checked rows in an array

I am trying to build a JQuery array with only the asp:gridviews that have been checked. However, I'm facing an issue where all rows are being added, regardless of their check status. How can I ensure that only checked rows are included in this array? ...

Delay the first image in Nivo Slider only

Wow, it actually works! Check it out here This solution was inspired by a thread on Stack Overflow about pausing Nivo Slider I managed to make the slider stop on the first image. Take a look at my code. I modified it to stop the animation twice so that ...

Choose a namespace node in jQuery

When I use YQL to fetch data using JSONP, it returns a string of XML. I then parse it using $.parseXML, place it inside a jQuery selector and attempt to select a node. However, the XML contains a namespace (such as yweather:) which causes jQuery to not fun ...

Implementing the 'keepAlive' feature in Axios with NodeJS

I've scoured through numerous sources of documentation, Stack Overflow threads, and various blog posts but I'm still unable to make the 'keepAlive' functionality work. What could I be overlooking? Here's my server setup: import ex ...

When trying to import SVGs using gatsby-plugin-react-svg, an error message stating "InvalidCharacterError: String contains an invalid character" is received

After realizing that my website's Largest Contentful Paint (LCP) might be affected by font-awesome svg icons, I decided to replace them. I extracted the svg code from my html and saved them as svg files. They appeared as images in my image editing sof ...

Passing Props from _app.js to Page in ReactJS and NextJS

I recently made the switch from ReactJS to NextJS and am encountering some difficulties in passing props from _app.js to a page. My issue lies in trying to invoke a function in _app.js from another page. In ReactJS, this process was simple as you could cr ...

When attempting to interact with a webpage using Python, Selenium is unable to successfully click the button on the

Currently, I am facing a challenge in clicking on a vote button present on a webpage using Python code. Even though I can successfully navigate to the page and interact with other elements like radio buttons, the vote button is not categorized as a "butt ...

Having trouble with JQuery toggle()? Need some assistance with fixing it?

My attempts to utilize JQuery toggle functionality have been unsuccessful. The sliding up and down animation is not smooth and instead happens very quickly. I aim to achieve a sliding effect in my code similar to this example (Please refer to Website Des ...

CSS and HTML modal not closing

I've been working on creating a custom popup using HTML, CSS, and some jQuery functions. My idea was that when I click on the main div, it should expand in size and display a cancel button, which it does successfully. However, the issue arises when tr ...

Tips for creating a new tab or window for a text document

Below code demonstrates how to open a new tab and display an image with a .jpg extension. Similarly, I want to be able to open a text document (converted from base64 string) in a new tab if the extension is .txt. success: function(data) { var ...

Incorporating multiple markers into Google Maps with the help of a JSON file

I am struggling to display markers on a map for 20 restaurants from a JSON file. It seems like I may not be retrieving the data correctly. Any help or guidance in the right direction would be greatly appreciated. My current code is as follows: var map; ...

What is causing the bootstrap switch to not align horizontally with the other elements within the div?

Here is the code snippet that I am working with: .global-wrap { display: flex; flex-direction: row; align-items: center; justify-content: center; } .header { width: 1024px; background-color: purple; padding: 7px; margin: 0; } div { ...

Why does Mongoose produce an array that cannot be iterated over when using Schema.find({})?

I am encountering a challenge while retrieving data from my mongo DB. The data that is returned contains everything I need, but it's in a peculiar structure that I'm struggling to navigate. I've attempted looping through it with a for loop, ...

submit django form when a checkbox is checked

tml: <div id="report-liveonly"> <form action="." id="status" method="POST">{% csrf_token %} <p>{{SearchKeywordForm.status}}Only display LIVE reports</p> </form> </div> I am facing an issue while trying to submit ...

Display a string of text containing multiple interactive links

I have a table and I want to create an interactive effect where, upon mouseover or click of certain elements, text will appear next to it. This text may contain multiple lines and clickable links within the content. For instance, in the table generated by ...

Is it possible to synchronously read a custom field from package.json?

Is there a way for users of my module to customize its functionality by defining a custom field in package.json? I'm struggling with reading it synchronously. If I need to read someField from the package.json file of an app or module that utilizes my ...

What is the process for setting `name` and `inheritAttrs` within the `<script setup>` tag?

Options API: <script> import { defineComponent } from 'vue' export default defineComponent({ name: 'CustomName', // ...