Conceal or reveal form elements based on input selection

In my current HTML form generated by PHP, I have multiple instances of the following structure:

function show(elem, show){
    var elements = 
    elem.parentNode.parentNode.parentNode.getElementsByClassName("hidden");
    var i;
    for(i=0; i<elements.length; i++){
    if(show){
    elements[i].style.display = "initial";
    }
    else{
    elements[i].style.display = "none";
    }
    }
}
.hidden {
    display: none;
    width: 100%;
    padding: 0px;
    margin: 2px;
    overflow: hidden;
}
<fieldset>
    <legend>Something</legend>

    <ul>
    <li>
        <input type="radio" name="X" value="No" onchange="show(this, false)">
        <label>No</label>
    </li>
    <li>
        <input type="radio" name="X" value="Yes" onchange="show(this, true)">
        <label>Yes</label>
    </li>
    </ul>

<p class="hidden">
    Elements
    </p>

    <fieldset class="hidden">
    Elements
    </fieldset>

</fieldset>

The goal is to show the class="hidden" elements when Yes is checked and hide them when No is checked, with them being hidden by default.

The issue arises when the form's status is loaded from a database and "Yes" can be pre-checked (in which case the corresponding html would be

<input type="radio" name="X" value="Yes" ...
). This requires an onload function, possibly using jQuery, to check if Yes is selected on load and then display the hidden elements. However, as my web design skills are limited, I am unsure how to proceed.

I acknowledge that my JavaScript and overall design may be messy, so any suggestions for improvement would be greatly appreciated.

EDIT

Following Joey Pinto's advice, here is the final implementation (including additional JavaScript):

$(document).ready( function(){
    var show=document.getElementsByClassName("shower");
    for(i=0;i<show.length;i++){
        if(show[i].checked){
            mostrar(show[i],true);
        }
    }
}
);

Additionally, the radio input for "Yes" has been assigned the class="shower".

Answer №1

Below is a handy JavaScript snippet for your reference

function show(elem, display){
    var elements = 
    elem.parentNode.parentNode.parentNode.getElementsByClassName("hidden");
    var i;
    for(i=0; i<elements.length; i++){
    if(display){
    elements[i].style.display = "initial";
    }
    else{
    elements[i].style.display = "none";
    }
    }
}

var yes_radio_button=document.getElementById("yes_radio");
if(yes_radio_button.checked){
show(yes_radio_button,true);
}
else{
show(yes_radio_button,false);
}
.hidden {
    display: none;
    width: 100%;
    padding: 0px;
    margin: 2px;
    overflow: hidden;
}
<fieldset>
    <legend>Something</legend>

    <ul>
    <li>
        <input type="radio" name="X" value="No" id="no_radio" onchange="show(this, true)" checked>
        <label>No</label>
    </li>
    <li>
        <input type="radio" name="X" value="Yes" id="yes_radio" onchange="show(this, true)" >
        <label>Yes</label>
    </li>
    </ul>

<p class="hidden">
    Elements
    </p>

    <fieldset class="hidden">
    Elements
    </fieldset>

</fieldset>

For further testing and exploration, feel free to visit the fiddle here

Answer №2

If you want to achieve this effect using only CSS, consider incorporating a checkbox into your design.
Utilize the :checked selector to trigger the display of specific content.

// Your CSS code 
input[type=checkbox] + label {
    color: #ccc;
    font-style: italic;
} 

// Specify the styling for the content when the checkbox is checked
// by utilizing the :checked CSS3 selector
input[type=checkbox]:checked + label {
    color: #f00;
    font-style: normal;
} 
<input type="checkbox" id="ossm" name="ossm"> 
<label for="ossm">CSS is Awesome</label>

Answer №3

To simplify your code, consider assigning a common class name to each of your <fieldset> elements. Then, you can iterate through all elements with this class name. This iteration will occur upon page load and for every checkbox event.

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 are the steps to clipping a canvas using CSS clip-path?

When it comes to clipping a canvas, there are multiple methods that can be used. One way is to create a path with getContext('2d') and set globalCompositeOperation. Another method involves using -webkit-clip-path or clip-path, though the latter m ...

Tips on connecting data within a jQuery element to a table of data

I am currently developing a program that involves searching the source code to list out element names and their corresponding IDs. Instead of displaying this information in alert popups, I would like to present it neatly within a data table. <script> ...

Automated tasks running on Firebase Cloud Functions with cron scheduling

There are two cloud functions in use: The first cloud function is used to set or update an existing scheduled job The second one is for canceling an existing scheduled job The management of scheduling jobs is done using import * as schedule from &ap ...

The error message indicates that the Worklight adapter is an object, not a function

Upon deploying the Worklight adapter to the production server, I encountered an error when the adapter called a Java code from JavaScript: Procedure invocation error. Ecma Error: TypeError: Cannot call property updateProposal in object [JavaPackage com.id ...

Unable to bring in @material-ui/core/styles/MuiThemeProvider

I'm currently working on a React project that utilizes Material UI React components. My goal is to import MuiThemeProvider in src/index.js with the following code snippet: import MuiThemeProvider from "@material-ui/core/styles/MuiThemeProvider"; . H ...

If the condition is true, apply a class with ng-class when ng-click is triggered

I am facing a situation similar to toggling where I am adding the class col-xs-6 to divide the page into two views. Initially, when I click, I set a variable value as true and in ng-class, I check for a condition to append the col-xs-6 class. Below is the ...

How can you connect a jQuery UI sortable component to an array?

Is there a way to connect a jQuery UI sortable element with an array in order to assign an index to each sortable element within the array? I am looking for a method to automatically sort the array based on the movement of the sortable elements. Any sugg ...

Certain scripts fail to load properly when using Internet Explorer

The code snippet provided only seems to be functional in Firefox, where it displays all alerts and successfully executes the displayUserLanding function. However, in Internet Explorer, the browser appears to only execute the following alert: alert("Helper ...

Syntax highlighting in custom blocks with VueJS

Vue single file components allow for the creation of custom blocks (besides the commonly used script, template, and style). For more information, you can refer to the official documentation here: . However, I am struggling to enable syntax highlighting w ...

Send an array using jQuery's $.post method

I am experiencing an issue with sending an array in $.post to PHP. When I use var_dump, the result is showing as "NULL" and JSON.stringify is not working. JQUERY var photobox = []; photobox.push(e.target.result); $.post("../modules/upload.php",{"imag ...

Sending an image dynamically as a prop to a child component

Within my parent component, I retrieve an object from an API which I later enhance with an image as a key/value pair. Subsequently, I pass this modified object to a child component for rendering. In order to accomplish this, I referred to the following pos ...

Angular: Issue with Controller Constructor Function Executing Repeatedly

My concern lies in the fact that the Controller constructor seems to be executing multiple times. It appears that if I have 2 Directives associated with a specific Controller, it runs 2 + 1 times, and for 3 Directives, it runs 3 + 1 times...and so on. This ...

How can I make my navbar stay fixed in place and also activate the transform scale functionality?

After fixing the position of my navbar with the class "top," I noticed that the transform property scale does not work on the div element I applied. The hover effect on the box only works when I remove the position from the navbar. This is the HTML code: ...

Sign up a new user using Passport JS

Looking to utilize passport.js for adding a new user from the signup page. The signup form is as follows: <form id="Signup-form" name="SignupForm" action="/signup" method="post"/> <input type="text" id="firstname" name="Firstname" > <input ...

Effective ways to manage extensive forms in Angular 2

I have a complex form in my application. What is the most effective way to collect data from this form and transmit it to the API using Angular 5? ...

When browserify is utilized, the error "function is not defined" may show up as an Un

Exploring an example at and attempting a function call as shown below: My HTML code is: <!DOCTYPE html> <html> <head> <title>Testing Browserify</title> <script src="bundle.js"></script> </head> <body& ...

Display an array of objects using React within the columns of a Bootstrap grid

I am facing a challenge where I have an array of components that I need to render in separate cells. The number of elements in the array can vary, sometimes exceeding the limit of 12 cells in the Bootstrap grid system. In such cases, I need to create new r ...

Incorporating an external SVG link into a React application

While I may not be an SVG expert, I haven't encountered any issues with loading SVGs in my React app so far. I prefer using the svg tag over the image tag because sizing tends to present problems with the latter option when working with external links ...

Unable to load the threejs module

I am still learning about threejs and have mostly worked on projects using a dev server (vite) locally. This setup limited me to accessing my projects only from the browser on my computer. Here is how I typically include my files in these projects: <bod ...

ng-if directive does not show data in AngularJS

I have a dynamic collection of images and videos that I want to display one at a time. Specifically, when I click on an image ID, I want it to show the corresponding image, and when I click on a video ID, I want it to show the relevant video. Below is the ...