What is the best way to write a JavaScript function that will reveal multiple fieldsets when a specific type is chosen?

In my webform, users can select a project type from a dropdown field and different sections will hide or display based on their selection. The array below contains the id's of the fieldsets and the corresponding values selected in the dropdown.

However, I have encountered an issue with a client request. They want two specific sections/fieldsets to appear when a particular project is selected, regardless of the project type. For instance, if the user selects 'Brochure' as the project type, the client wants both the 'Brochure' section/fieldset and another fieldset named "Brief Details" (id: 556) to be displayed.

The problem is that adding "{id : '556', value:'Brochure'}" to the array causes the "Brief Details" section/fieldset to display, but it hides the "Brochure" fieldset that should also be visible. I understand why this is happening but are struggling to make the necessary adjustments in the JavaScript code.

So how can I modify the existing code to ensure that when the project type selected is 'Brochure', both fieldset 556 and 159 are shown?

var projectTypes = new Array (
    {id : '123', value:'Banner'},
    {id : '456', value:'Ad'},
    {id : '789', value:'Graphics'},
    {id : '987', value:'Billboard'},
    {id : '654', value:'Booklet'},
    {id : '321', value:'Tickets'},
    {id : '147', value:'Window'},
    {id : '159', value:'Brochure'}
    );

/*function below occurs onChange event of project type dropdown:*/
refreshSections(project_type);  

/*
 *  Function used to hide/show sections based on selected project type
 */
function refreshSections(selectedType) 
{   
    for (var i = 0; i < projectTypes.length; i++) 
    {
        if (projectTypes[i].value == selectedType) 
        {
            document.getElementById("section-"+ projectTypes[i].id).style.display = '';
        } else {
            document.getElementById("section-"+ projectTypes[i].id).style.display = 'none';
        }
    }   
}

Answer №1

Instead of using a single ID, how about using an array:

{id : ['159','556'], value:'Brochure'}

In the function code, you could modify it to:

if (projectTypes[i].value === selectedType) {
  if (typeof projectTypes[i].id == "object") {
    var targets = typeof projectTypes[i].id;
    for (var j = 0, l = targets.length; j < l; j++) {
      document.getElementById("section-"+ targets[j]).style.display = '';
    }
  } else {
    document.getElementById("section-"+ projectTypes[i].id).style.display = '';
  }
} else {
  document.getElementById("section-"+ projectTypes[i].id).style.display = 'none';
}

I haven't extensively tested it... Maybe consider creating a fiddle with some markup and JS code for easier troubleshooting

Answer №2

If you have the flexibility to make changes to the code and html, one suggestion would be to expand the projectTypes array by adding another value. The structure could vary, but as an example:

var projectTypes = new Array (
    {id : '556', value:'Brief Details', showSections: [556, 159]}
);

You can also consider giving all 'hideable sections' a common classname:

<div id="section-156" class="hideable-section"><!--content--></div>

Then, update your function to utilize that property for customization:

function refreshSections(selectedType) {   
    var i, j;
    //Hide everything by default (e.g., using document.getElementsByClassName('hideable-section'))
    for (i = 0; i < projectTypes.length; i++) {
        if (projectTypes[i].value == selectedType) {
            if(projectTypes[i].showSections != null) {
                for(j = 0; j < projectTypes[i].showSections.length; j++){
                    document.getElementById("section-"+ projectTypes[i].showSections[j].toString()).style.display = '';
                }
            }
            else {
                document.getElementById("section-"+ projectTypes[i].id).style.display = '';
            }
        }
    }   
} 

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

Optimizing Backend Access with Laravel and Vue JS: How to Choose the Most Effective Approach

Currently, I am utilizing Laravel API passport to handle authentication in my Single Page Application (SPA) built with Vue. At the moment, whenever I need to access the backend server, I have to include a header in order to be allowed through the protected ...

Utilizing asynchronous programming for scenarios where two requests need to be sent, with the response from the first request being required for the second request

I have an async function that looks like this: exports.myFunction = async (req, res, next) => { if (some condition) { next() } try { const results = await axios.get(`https://a-domain.com/url/path`); const info = results.data; c ...

Exploring nested arrays in VueJS

When working with a prop that contains an array within an array, I find myself having to iterate through multiple v-for statements in order to access the desired data. Currently, my process involves cycling through the spaces array to match the ids and th ...

Convert cURL requests into xmlhttprequest

Could anyone provide guidance on how to convert the given curl command into an ajax/xmlhttpsrequest format? curl -d "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04717761766a65696139717761766a65... I have attempted to repli ...

Preventing event propagation in jQuery's click handler

Is it possible to prevent the propagation of a click event on a dynamically created div within its parent div? HTML <div id = "parent"> Some Stuff </div> Jquery $('#parent').click(function(){ $(this).append('<div class = ...

When using Vue2, pushing a string to an array simply replaces the existing string instead of appending it

My current task involves manipulating a local data array by adding and removing strings within a method. However, I have noticed that my logic always results in the array containing only a single string passed to the updateIdArr method. Even after removin ...

Display the active item in ng-repeat using conditional ui-view

Here is the situation: I'm working with a list of items that are displayed using ng-repeat. Each item has its own template. When a user clicks on an item, that particular item is marked as "active" and gets a different template compared to the rest ...

The values stored in localStorage do not carry over to other pages

Why is the value of localStorage not persisting on other pages when I am using it in my app? Is this a limitation or am I possibly making a mistake? Here is my code snippet: if(!localStorage.getItem("myDataList")){ localStorage.setItem("myDataList" ...

retrieve information in json format from a specified web address

I need to figure out why the data from a specific URL is not being displayed properly on my node application. It seems like there might be an error in my code. const extractRefDefaultSchema = async (data) => { const url = "https://mos.esante.gouv.f ...

Verify if the radio element is marked as selected in the AJAX reply

My ajax response contains two radio elements and I need to check if they are checked in the response. I've tried using the code below to check the radio status but it's not working: $('#input[type=radio]').each(function(){ alert($( ...

Am I on the right track with incorporating responsiveness in my React development practices?

Seeking advice on creating a responsive page with React components. I am currently using window.matchMedia to match media queries and re-rendering every time the window size is set or changes. function reportWindowSize() { let isPhone = window.matchMed ...

What seems to be the issue with this Discord.js kick command code? It's not

Okay, so I'm in the process of creating a kick command for my Discord bot. The issue I'm encountering is that when no reason is specified or if a user is not mentioned to be kicked, the bot responds correctly but does not actually kick the user. ...

Development is hindered due to Cors policy restricting access to the localhost webapp

Currently, I am working on developing a web application and an API simultaneously, but I'm facing some issues with CORS blocking. This concept is relatively new to me, and I'm eager to improve my understanding. Firstly, I have set up an Express ...

The .each function in JavaScript is creating conflicts with other classes on the webpage

HTML <ul class="courseDates"> <li class="dateOne col-sm-2"> {tag_course date 1} </li> <li class="dateTwo col-sm-2"> {tag_course date 2} </li> <li class="dateThree col-sm-2"> { ...

Attempting to organize various submission buttons

Seeking assistance on how to handle multiple submit buttons. I am attempting to trigger a JavaScript function "pull()" when the user clicks the play button, and I want to execute a PHP script "score.php" when the user clicks the save button. <form id=" ...

What is the best way to access the image source attribute within a directive?

Here's a straightforward image directive example: (function () { 'use strict'; angular .module('myapp') .directive('imageTest', imageTest); function imageTest() { var directive = { ...

What could be causing the `unstable_Profiler` to not function properly in production mode?

Encountering a problem with unstable_Profiler in my React-Native project where the onRender callback is being ignored, but only in production mode. No errors are being thrown and everything renders correctly. I followed the advice from this article: I tes ...

Finding an element that lacks both a class and an id, and is not consistently present - what's the trick?

Currently, I am faced with a predicament in my code where a <li> element only appears under specific conditions, making it difficult to apply positioning. This element lacks an id and class attribute, which prevents me from targeting it accurately us ...

Exploring ways to manipulate checkboxes using jQuery for enhanced form validation

I am working on a custom validation for four fields, with one required to be filled in. However, I am facing an issue where the validation process is interfering with the functionality of my checkboxes. Once the jQuery click function runs, the checkboxes a ...

Is there a restriction on the number of Chrome Webdriver instances allowed

I have been attempting to launch multiple Node instances using the Chrome webdriver on an Amazon EC2 server. However, I have encountered a problem where once I reach a total of 84 node instances, Selenium throws an error: Build information: version: &apos ...