Display the table once the radio button has been selected

Before we proceed, please take a look at the following two images: image 1 image 2

I have over 20 fields similar to 'Image 1'. If "Yes" is selected, then a table like in 'Image 2' should be displayed. This means I have 20 Yes/No fields and 20 different tables. What is the best way to display these tables when "Yes" is selected? I have tried some code for a single field, but with multiple fields, I am looking for a more minimal and easier solution. Below is the code snippet that I experimented with:

CSS:

#show-dc-table {
  display: none;
}

Script:

<script>
$(document).ready(function() {
  $('.form-check-inline input[type="radio"]').click(function() {
    if ($(this).attr('id') == 'allergy-yes') {
      $('#show-dc-table').show();
    } else {
      $('#show-dc-table').hide();
    }
  });
});

</script>

HTML:

<div class="form-group row">
  <label class="col-sm-2 col-form-label">Do you have Allergies </label>
  <div class="col-sm-10">
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" name="allergy" value="Yes" id="allergy-yes">
      <label class="form-check-label">Yes</label>
    </div>
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" name="allergy" value="No">
      <label class="form-check-label">No</label>
    </div>
  </div>
</div>
<table class="table table-striped" id="show-dc-table">
  <tr>
    <th scope="col">Alergic Reactions to</th>
    <th scope="col">Yes</th>
    <th scope="col">No</th>
    <th scope="col">Notes</th>
  </tr>
</table>


Answer №1

To effectively manage multiple repeated HTML structures, organize elements by behavior using a consistent class for each group. Utilize DOM traversal to establish relationships between elements when specific events occur.

In your scenario, utilizing closest() and next() will help locate the appropriate table associated with the changed radio button. Remember to use the radio button's checked attribute in conjunction with the change event to identify the selected value. Try implementing this approach:

$(document).ready(function() {
  $('.form-check-inline input[type="radio"]').on('change', function() {
    $(this).closest('.form-group').next('table').toggle(this.checked && this.value === 'Yes');
  });
});
.show-dc-table {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="form-group row">
  <label class="col-sm-2 col-form-label">Do you have allergies?</label>
  <div class="col-sm-10">
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" name="allergy" value="Yes">
      <label class="form-check-label">Yes</label>
    </div>
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" name="allergy" value="No">
      <label class="form-check-label">No</label>
    </div>
  </div>
</div>
<table class="table table-striped show-dc-table">
  <thead>
    <tr>
      <th scope="col">Allergic Reactions to</th>
      <th scope="col">Yes</th>
      <th scope="col">No</th>
      <th scope="col">Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Aspirin, Ibuprofen, Codeine</td>
      <td><input type="radio" name="a1" /></td>
      <td><input type="radio" name="a2" /></td>
      <td><input type="text" /></td>
    </tr>
  </tbody>
</table>

<div class="form-group row">
  <label class="col-sm-2 col-form-label">Do you have a cough?</label>
  <div class="col-sm-10">
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" name="cough" value="Yes">
      <label class="form-check-label">Yes</label>
    </div>
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" name="cough" value="No">
      <label class="form-check-label">No</label>
    </div>
  </div>
</div>
<table class="table table-striped show-dc-table">
  <thead>
    <tr>
      <th scope="col">Coughing Sensitivity to</th>
      <th scope="col">Yes</th>
      <th scope="col">No</th>
      <th scope="col">Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Lorem ipsum</td>
      <td><input type="radio" name="a1" /></td>
      <td><input type="radio" name="a2" /></td>
      <td><input type="text" /></td>
    </tr>
  </tbody>
</table>

Answer №2

For optimal DOM manipulation, it is recommended to avoid using hardcoded ids and instead utilize methods such as closest, find, next, and prev. In the given example, the closest and find methods are employed.

$(document).ready(function() {
  $('.form-check-inline input[type="radio"]').click(function() {
    if ($(this).val() == 'Yes') {
      $(this).closest('.form-group').next('table').show();
    } else {
      $(this).closest('.form-group').next('table').hide();
    }
  });
});
.table.table-striped {
  display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="form-group row">
  <label class="col-sm-2 col-form-label">Do you have Allergies </label>
  <div class="col-sm-10">
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" name="allergy" value="Yes" id="allergy-yes">
      <label class="form-check-label">Yes</label>
    </div>
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="radio" name="allergy" value="No">
      <label class="form-check-label">No</label>
    </div>
  </div>
</div>
<table class="table table-striped" id="show-dc-table">
  <tr>
    <th scope="col">Alergic Reactions to</th>
    <th scope="col">Yes</th>
    <th scope="col">No</th>
    <th scope="col">Notes</th>
  </tr>
</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

Make sure to close any existing Featherlight windows before trying to open another one

I'm setting up multiple featherlight instances when the page loads jQuery('.feedback').featherlight(jQuery( "#feedback-box" ), { closeIcon: 'close'}); jQuery('#imprint').featherlight(jQuery( "#imprint-box" ), { closeIcon ...

I'm having trouble understanding the distinction between this.query and this.query.find(). Can you explain the difference to me?

Currently, I am working on a MERN tutorial where I am developing a full E-commerce application. This is the class that handles querying and various other tasks. constructor(query, querystr) { this.query = query; this.querystr = querystr; con ...

Combine two arrays and collapse one of the nested elements

I need help merging two arrays based on ID and flattening one of the objects. I haven't been able to find a solution for my specific case. This is what I'm attempting and what I've managed to achieve so far: const a = { someProperty: &a ...

Is it possible to monitor the progress of an order placed via my website as a Flipkart affiliate?

As an affiliate for flipkart, I promote their products on my website. I am interested in being able to track the orders and purchases made by users who are redirected to flipkart from my site. Is it possible for us to obtain the order/purchase id for thos ...

Implementing optimal techniques to create a JavaScript file for data retrieval in a Node.js application

I've developed a file specifically for data access purposes, where I'm keeping all my functions: const sql = require('mssql'); async function getUsers(config) { try { let pool = await sql.connect(conf ...

Styles in CSS for the first column of a table, with the exception of the first cell in

Here is the HTML code for a table: <table class='census'> <tr> <th colspan="2">My Title</th> </tr> <tr> <td colspan="2" class='chart'><SOME PIE CHART, GENERATED W ...

The Jquery image on.load event seems to only function properly after performing a manual hard refresh of

Looking for a solution to replace loading text with a button only after the image has loaded onto the page. Utilizing on.load as follows: $('img.house').on('load', function() { $('.loading').hide(); $('# ...

Prevent manual scrolling with CSS

I've incorporated CSS smooth scrolling into my project, which is activated by clicking a specific div element. My current goal is to prevent manual scrolling on the page so that users can only navigate by clicking the designated div and not by conven ...

What are some methods for applying border styles to the first and last row of a table using Material UI?

In my current project, I am utilizing the combination of Material UI and React Table. Recently, I was asked to implement an expandable row feature, which I successfully added. Once the user expands the row, we need to display additional table rows based on ...

Error encountered while establishing connection with MongoClient

My server is returning the following error message: MongoClient.connect('mongodb://<'yoda'>:<'yoda69'>@ds235778.mlab.com:35778/satr-wars-quotes', (err, client) => { ^^^^^^^^^^^^^ SyntaxError ...

Improve the way you manage the active selection of a button

ts isDayClicked: { [key: number]: boolean } = {}; constructor() { } setSelectedDay(day: string, index: number): void { switch (index) { case 0: this.isDayClicked[0] = true; this.isDayClicked[1] = false; this.isDay ...

What is the best way to make my <div> element expand to fill the entire width of the screen? I attempted setting the width to 100%, but it didn

I need help creating a <div> that spans the entire width of the screen. In my CSS, I have this code: #spacer3 { width:100%; height:300px; } Although it seems like it should work, the div is not extending all the way to the edges of the screen on ...

Leveraging the source of an image from asset variables

Lately, I've been experiencing issues with displaying images on my page, specifically when trying to show a list of images. The problem arises when attempting to store the image URL in a variable or object instead of hardcoding it directly into the s ...

Lock in the top row (header row)

In a node.js application: How can I lock the top row of a table in place, similar to Excel's freeze panes feature? I think this might involve using some CSS styling, but I'm not exactly sure how to achieve it. When I tried using fixed, the entir ...

Ways to fix the loading error in AngularJS version 1.3.5?

My HTML page includes AngularJS components. Below is the code snippet: <!DOCTYPE html> <html ng-app="MyApp"> <head> <base href="/"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> &l ...

Be warned: Babel has detected a duplicate plugin or preset error

Currently, I am enrolled in a React course on Frontend Masters. As part of the course, we were tasked with modifying the Babel config to allow state instantiations like: state = {index: 0} in class components. However, when I executed the command: npm i ...

The Reactjs dependency tree could not be resolved

In my current project, I've been attempting to integrate react-tinder-card. After running the command: npm install --save react-tinder-card I encountered this error in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency ...

Using Formik with Material UI's TextField component and passing a 'label' prop to the Field component

Currently, I am in the process of creating a form with Formik and Material UI. I have implemented the Formik component as follows: Within my Input component, the following code is used: const Input = ({ field, form: { errors } }) => { const errorMes ...

Problem with Flickity's is-selected feature

I am currently exploring Flickity and its functionality. I have a carousel that auto-plays, with the selected cell always placed in the middle and highlighted with a grey background. However, I would like to customize it so that the selected cell is positi ...

Restrict the height of a division based on the adjacent division

Within the parent div, I have two child div elements that are meant to be positioned side by side. The first element contains an image which loads dynamically, meaning its height is unknown in advance. I want the parent div's total height to match the ...