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

Deleting elements from the DOM in Vue.js

Utilizing Vue.js (version 3.x), I am dynamically rendering components. <div v-for="(i, index) in fields" > <my-component :id="index" ></my-component> <span class="delete-icon" @click="removeFi ...

The value returned is undefined when using getStaticProps

Recently, while working on my project with Next.js, I encountered an issue where I was trying to access data but kept getting undefined. Below is the code snippet that I was working with: function Home({books}) { console.log(books) return <div>Home ...

Is it possible to manipulate the attribute of an object using Object.defineProperty when a value is passed as a function parameter?

As I delve into understanding reactivity in Vue, the concept of how reactivity is achieved when passing a value as a function parameter perplexes me. //here is the actual code snippet var obj = {a: 'aa'} function reactive(obj, key, value) { ...

What is the best way to retrieve a property with a period in the method name in JavaScript?

One dilemma I'm facing is trying to access the tree.removenode method through chartContext in Angular. It's been a challenge for me to understand how to achieve this. https://i.stack.imgur.com/yG7uB.png ...

Adding external JavaScript files that rely on jQuery to a ReactJS project

As a beginner in web development, I have a question regarding importing external JavaScript files in ReactJS. I currently have the following imports: import $ from 'jquery'; window.jQuery = $; window.$ = $; global.jQuery = $; import './asse ...

Update HTML element using Jquery periodically

I have a PHP script that updates me with the upcoming bus departure time. Currently, I am using jQuery to refresh this information in a div every minute. However, since I know when the data will change (after the bus arrives), I want the div to refresh at ...

Struggling to get the jQuery resize event to function properly

Ensuring that my charts remain responsive on different devices has been quite a challenge. Despite implementing a resize event handler in my function to dynamically adjust the charts, I encountered an issue where the page would go blank upon resizing the b ...

Encountering a Javascript Error when trying to begin

As a beginner in Javascript, I am venturing into designing a simple website that incorporates Javascript. Currently, my focus is on building a calculator. However, upon loading my website, nothing seems to initiate and there are no error messages displayed ...

Customize date filtering in KendoUI grid

I am trying to modify the date format in the filter of my kendo grid. For example, I would like to change 1/30/2015 to Jan 30, 2015 I have successfully changed the date format for Start Date field: "StartDate", title: " ...

Is it possible for a table row's cell to determine the value of the cell in the row above it?

Let me illustrate my issue with an example. Consider the following table: <table> <tr> <th>First</th><th>Second</th><th>Third</th> </tr> <tr> <td>A</td><t ...

Maintain correct aspect ratio when zooming in the body

I'm facing a challenge with my single-page web application that has fixed width and height. It doesn't scale properly to fit the page at all times. Scaling based on its width works fine, but I want to achieve scaling from both width and height w ...

The Django CSRF token is inaccessible for retrieval

I'm in the process of developing a website using Vue.js for the frontend and Django for the backend. I've made sure to include the csrf token in every request from the frontend to the backend to prevent any 403 Forbidden errors. All requests are ...

Having trouble getting the finally clause to work properly in Angular JS version 1.7

In my current project, I am utilizing Angular JS 1.7. Recently, I encountered an issue while using the finally clause within a promise: $http.put( url, null, { headers: { 'Content-Type': 'application/json' } } ).then( ...

Dynamically implementing event listeners in JavaScript to remove specific elements based on their

My website has a list of phones displayed as ul li. When a user clicks the "Buy" button, it should create a new li within another div called "ordersDiv". Users can delete their purchase from the cart by clicking "Remove", which should remove the li with ma ...

Access your Vue.js application using Google Sign-In (GIS)

Having trouble with the discontinuation of gapi.oauth2 by Google and finding the new Sign in With Google tools confusing. Project Structure Looking to implement user sign-in with Google on my Vue frontend and authenticate them using OIDC server flow on ...

Print Vue page with the same styling as the original

How can I add a print button to my application that prints the page with the original CSS styles? I am currently using window.print() function and have a separate file called print.scss with specific print styles. @media print { header {display:none; ...

Tips on how to collapse all elements whenever one is being opened in a FAQ card using ReactJS

Clicking on a question reveals its text, and clicking on another collapses the previous one. The issue arises when trying to close an open question by clicking on it again - it doesn't work as intended due to a potential error in the If statement [im ...

Shifting an element to the right before revealing or concealing it with Jquery Show/Hide

$(document).ready(function(){ var speed = 700; var pause = 3500; function removeFirstElement(){ $('ul#newsfeed li:first').hide('slide', {direction: "up"}, speed, function() {addLastElement(thi ...

Issue with drop-down menu functionality on mobile-friendly website

After deciding to revamp my website for responsiveness, I encountered an issue with the menu not displaying on smaller screens. Everything else is functioning correctly except for the drop-down menu! Here is the HTML code: <!doctype html> <html ...

Having Trouble Retrieving Environment Variables in Next.js API Endpoints

Currently, I am in the process of working on a project utilizing Next.js 13 and API routes to communicate with a database. My goal is to securely store my database credentials in a .env file, but unfortunately, the variables are not loading as expected. I ...