A guide on how to modify a CSS property to set the display to none upon clicking a radio button

Currently, I am attempting to display two input boxes in a table when I select specific radio buttons and hide them if I choose another option. The code I have does work but has a minor issue,

function disappear() {
  document.getElementsByClassName("table-custom3")[0].style.display = 'none';
}

function appear() {
  document.getElementsByClassName("table-custom3")[0].style.display = 'block';
}
<table>
  <tr>
    <td class="table-custom2">
      <input type="radio" id="present" name="attendance" onclick="appear()" /</td>
      <td class="table-custom2 "><input type="radio" id="absent" name="attendance" onclick="disappear()" /</td>
        <td class="table-custom3 "><input type="time " class="input-xsmall "></td>
        <td class="table-custom3 "><input type="time " class="input-xsmall "></td>
  </tr>
</table>

The issue with this code is that it only applies to the first user input. I attempted to change from getElementById to getElementsByClassName, but only one textbox appeared. Is there a solution for this problem?

I also came across a Jquery code that seems simpler to execute, but I couldn't find a tutorial on how to apply it to my situation. Any advice on that would be greatly appreciated.

Answer №1

Utilize a loop to toggle the visibility of all elements with a specific class.

Additionally, remember to apply the style inline-block instead of block to keep them on the same row.

function hideElements() {
  Array.from(document.getElementsByClassName("table-custom3")).forEach(el => el.style.display = 'none');
}

function showElements() {
  Array.from(document.getElementsByClassName("table-custom3")).forEach(el => el.style.display = 'inline-block');
}
<table>
  <tr>
    <td class="table-custom2">
      <input type="radio" id="present" name="attendance" onclick="showElements()" /></td>
    <td class="table-custom2 "><input type="radio" id="absent" name="attendance" onclick="hideElements()" /></td>
    <td class="table-custom3 "><input type="time " class="input-xsmall "></td>
    <td class="table-custom3 "><input type="time " class="input-xsmall "></td>
  </tr>
</table>

Answer №2

If you're looking for a way to dynamically change the state of a sibling element, one approach is to utilize toggling classes based on the current state.

Here is an example:

.table-custom2.enabled ~ .table-custom3 { display: block; }
.table-custom2.disabled ~ .table-custom3  { display: none; }
function enableSwitch() {
  document.querySelector(".table-custom2").classList.replace("disabled", "enabled");
}

function disableSwitch() {
  document.querySelector(".table-custom2").classList.replace("enabled", "disabled");
}

Answer №3

To ensure that getElementsByClassName works correctly, it is important to enclose your code within a table tag. Additionally, since getElementsByClassName returns an array of elements, you will need to access them by index as shown below:

[...document.getElementsByClassName("table-custom3")].map((item)=> {item.style.display = 'none'});

Here is an example illustrating how this can be implemented:

function absentSwitch() {

    [...document.getElementsByClassName("table-custom3")].map((item)=> {item.style.display = 'none'});

}
function presentSwitch() {
    [...document.getElementsByClassName("table-custom3")].map((item)=> {item.style.display = ''});

}
<table>
<tr>
<td class="table-custom2"><input type="radio" id="present" name="attendance" onclick="presentSwitch()" /></td>
<td class="table-custom2"><input type="radio" id="absent" name="attendance" onclick="absentSwitch()" /></td>
<td class="table-custom3"><input type="time" class="input-xsmall"></td>
<td class="table-custom3"><input type="time" class="input-xsmall"></td>
</tr>
</table>

Answer №4

Below is the HTML code snippet for handling multiple inputs in a table:

<table>
    <tr>
      <td class="table-custom2">
        <input type="radio" id="present" name="attendance" onclick="presentSwitch(this) "/></td>
        <td class="table-custom2 "><input type="radio" id="absent" name="attendance" onclick="absentSwitch(this) " /</td>
          <td class="table-custom3 "><input type="time " class="input-xsmall "></td>
          <td class="table-custom3 "><input type="time " class="input-xsmall "></td>
    </tr>
  </table>

Here are the corresponding JavaScript functions:

function absentSwitch(event) {
     event.parentElement.parentElement.children[2].style.display = 'none';
     event.parentElement.parentElement.children[3].style.display = 'none';
}
function presentSwitch(event) {
     event.parentElement.parentElement.children[2].style.display = 'block';
     event.parentElement.parentElement.children[3].style.display = 'block';
}

You are now able to effectively manage multiple input elements within a table.

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

Ways to activate a stylish pop-up box using an input field (when focus is removed)

While attempting to activate Fancybox upon the user shifting focus away from an input field containing a value greater than 25, everything seems to be in order with the focus out and value checking code. Nevertheless, when Fancybox is triggered, the follow ...

Searching for nicknames in a worldwide Jest arrangement?

Before running all test cases, I need to execute certain tasks only once. To achieve this, I have created a global function and specified the globalSetup field in my Jest configuration: globalSetup: path.resolve(srcPath, 'TestUtils', 'global ...

Enable landscape mode exclusively for tablet and mobile devices, excluding desktop users

Looking to rotate content on tablet and mobile devices without affecting desktop view. Attempted solutions: rotate(90deg) -> Didn't work as it rotated even on desktop @media screen and (orientation:lanscape) -> Also didn't work as it ...

Inserting data into a Textbox by clicking on a Div

I'm currently working on creating a wallpaper changer for my website. Right now, I'm looking to input the URL of a wallpaper into a text box when the corresponding DIV option in a CSS menu is clicked. Below is the JQuery I am using: $("div.bg8 ...

Material UI Grid List rows are displaying with an unusually large gap between them, creating a

Currently, I am utilizing Material UI in combination with Reactjs. One particular issue that I am encountering involves the Grid List Component. In my attempt to establish a grid of 1000x1000px, I have specified the height and width within the custom gridL ...

Default page featuring an AngularJS modal dialog displayed

I am attempting to display a modal popup dialog using an HTML template. However, instead of appearing as a popup dialog, the HTML code is being inserted into the default HTML page. I have included the controller used below. app.controller('sortFiles&a ...

Updating nested forms in Angular 4

The nested form structure I am working with is a 'triple level' setup: FormGroup->ArrayOfFormGroups->FormGroup At the top level (myForm): this.fb.group({ name: '', description: '', q ...

Understanding the concept of for loops in JavaScript and incorporating them in CSS styling

Hello there! I initially used this code to draw 12 lines, but now I am looking to incorporate a for loop and implement it in CSS. Can someone please guide me on how to proceed? <!DOCTYPE html> <html> <head> <style> #straigh ...

Nested promise not being waited for

As someone new to all things asynchronous, I am currently facing a challenge. I want to ensure that a file exists before updating it, creating the file if necessary. However, I am struggling to figure out how to achieve this. I am aware of the option to u ...

Retrieve information from every nested array and present it in sequential order

I need to extract the index of each element in a nested array structure. For example, I have an array with 5 subarrays, each containing multiple elements. My goal is to retrieve the first element from each subarray, then the second element, and so on. Her ...

Customize the colors of the arrows in Bootstrap's carousel

There seems to be a simple solution that I'm missing here. I have images with white backgrounds and I want to customize the arrows on Bootstrap's Carousel to make them more visible. I need help changing the color of the arrows (not the background ...

Are you seeing empty squares in place of Font Awesome icons?

If the Font Awesome icons are displaying as blank squares in all browsers despite correctly linking the stylesheet and attempting to install the package through npm which results in a npm ERR! code E401, it can be frustrating. Even after checking the brows ...

Odd behavior from CSS

Running into a bit of a snag with my website lately, specifically with the CSS. As I'm relatively new to web design, these issues tend to crop up more frequently. Usually, I can solve them on my own, but this one has me completely puzzled. What' ...

What sets apart the CSS file directories in a React application compared to those in an Express server?

For instance, there is a public folder that contains all the css files, and a separate view folder for ejs files. When linking the css file in the ejs file, the code usually looks like this: <link rel=”stylesheet” href=”styles.css”> or like ...

Removing outline from a Material UI button can be done using a breakpoint

Is there a way to remove the outlined variant for small, medium, and down breakpoints? I have attempted the following approach: const selectedVariant = theme.breakpoints.down('md') ? '' : 'outlined'; <Button name="buy ...

Displaying items in the shopping cart across two separate columns

I have a website located at Within that page, I have included the Cart table using a woocommerce shortcode. Currently, the cart table is positioned below the billing details and payment options section. My goal is to move this cart table to be situated ...

App script: Extracting HTML form data from a web application

I have been trying to work on a script that involves taking input from an HTML form and processing that data in order to populate a Google Sheet. Unfortunately, I haven't had much success with it so far. Here is the code I have been working on: Index ...

Request queuing using jQuery with a time delay

I have a form that allows users to send messages on a forum. Using jQuery $.ajax post request, these messages are sent every 35 seconds as per the Security Policy Forum. In this form, I input the name of the user and the text for the message in the corres ...

Store the text area content as a JSON object

What is the best way to store the content of a textarea in JSON format? I am currently working on a project where I have a textarea element and I need to save its value into a JavaScript object. Everything is functioning correctly except when 'enter ...

Implementing Knockout.js with JqueryUI Autocomplete: Access the complete object instead of just the value

I have implemented a custom binding for a JQueryUI auto complete feature that works well. However, I am looking to modify it so that it returns the Item object, which can then be pushed to another array. Can someone provide guidance on how to achieve this ...