Unveiling Extra Form Fields Based on Selected Radio Buttons using html and css

I need to display different form fields depending on whether the credit card radio button or debit card radio button is selected. Currently, when I select a radio button, only the corresponding form fields are visible.

Current Code

<div class="forcredit">
  <label>Card no:</label>
  <input type="text" name="cardno" required=""><span style="color: red;">*</span>
  <label>CVV no:</label>
  <input type="text" name="cvvno" required=""><span style="color: red;">*</span>
  <label>Expiration MM/YYYY</label>
  <input type="month" name="expire" required=""><span style="color: red;">*</span>
</div>

The issue is that I want both sets of form fields to be displayed when I press each respective radio button, but currently only one set is showing at a time.

Here is my complete code:

<!DOCTYPE html>
<html>
<head>
    <title>form</title>
</head>
<body>
  <form method="post" action="#">
  
  <h4>Payment type:</h4>
  <div>
    <div>
      <input type="radio" name="credit" id="credit" required>
      <label>Credit card</label>
    
      <div class="forcredit">
      <label>Card no:</label>
      <input type="text" name="cardno" required=""><span style="color: red;">*</span><br>
      <label>CVV no:</label>
      <input type="text" name="cvvno" required=""><span style="color: red;">*</span><br>
      <label>Expiration MM/YYYY</label>
      <input type="month" name="expire" required=""><span style="color: red;">*</span><br>
      </div>
    </div>
    
    <div>
      <input type="radio" name="debit" id="debit">
      <label>Debit card</label>
    
      <div class="fordebit">
      <label>Card no:</label>
      <input type="text" name="cardno" required=""><span style="color: red;">*</span><br>
      <label>CVV no:</label>
      <input type="text" name="cvvno" required=""><span style="color: red;">*</span><br>
      <label>Expiration MM/YYYY</label>
      <input type="month" name="expire" required=""><span style="color: red;">*</span><br>
      </div>
    </div>
  </div>
  <div>
    <input type="submit" value="Pay">
  </div>
  </form>
</body>
</html>

I am looking for help in adjusting the CSS file so that both sets of form fields can be displayed simultaneously when each radio button is clicked.

Answer №1

To show the next sibling in CSS, you need to use the :checked selector.

  input[type=radio] + .fordebit,
  input[type=radio] + .forcredit{
    display:none;
  }
  input[type=radio]:checked + .fordebit{
     display:block;
  }
  input[type=radio]:checked + .forcredit{
     display:block;
  }
UPDATE

An update has been made to your code with corrections for the HTML structure as well. For radio buttons used for multiple choice items, they should have the same name. See the updated working code below:

input[type=radio] + .details{
  display: none;
}

input[type=radio]:checked + .fordebit {
  display: block;
}

input[type=radio]:checked + .forcredit {
  display: block;
}
input[type=radio] {
  float:left;
}
<form method="post" action="#">

  <h4>Payment type:</h4>
  <div>
    <div>
      <label>Credit card</label>
      <input type="radio" name="payment_type" id="credit" required>

      <div class="forcredit details">
        <label>Card no:</label>
        <input type="text" name="cardno" required=""><span style="color: red;">*</span>
        <br>
        <label>CVV no:</label>
        <input type="text" name="cvvno" required=""><span style="color: red;">*</span>
        <br>
        <label>Expiration MM/YYYY</label>
        <input type="month" name="expire" required=""><span style="color: red;">*</span>
        <br>
      </div>
    </div>

    <div>
      <label>Debit card</label>
      <input type="radio" name="payment_type" id="debit">

      <div class="fordebit details">
        <label>Card no:</label>
        <input type="text" name="cardno" required=""><span style="color: red;">*</span>
        <br>
        <label>CVV no:</label>
        <input type="text" name="cvvno" required=""><span style="color: red;">*</span>
        <br>
        <label>Expiration MM/YYYY</label>
        <input type="month" name="expire" required=""><span style="color: red;">*</span>
        <br>
      </div>
    </div>
  </div>



  <div>
    <input type="submit" value="Pay">
  </div>

Answer №2

It's not possible to achieve this using just CSS. JavaScript becomes crucial for capturing events in such cases. By leveraging a tool like jQuery, you will have to link a click event handler to the radio button selector for cards. Verify the names of your radio buttons first before implementing code similar to this:

$('.card').click(function() {
  $('.forcredit').show();
});

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

I'm looking for a way to display a modal when a button is clicked and no record is selected from my table. My project is utilizing Bootstrap 4

<table id="resultTable" class="table table-hover table-bordered table-sm"> <thead> <tr> <th>Select</th> <th>Message Id</th> <th>Service</th> <th>Date</th> & ...

The Jquery validation in Asp.Net MVC 5 does not seem to work properly when using ajax post during a submit event, as it incorrectly

I've double-checked all the necessary elements for client-side validation, but unfortunately, the validation is still not working. I would greatly appreciate it if someone could assist me in identifying what I might have overlooked or where I may hav ...

Does one require the express.js framework in order to create a web application using nodeJS?

Exploring the creation of a basic web application using HTML, NodeJS, and Postgres. Can this be achieved without incorporating the ExpressJS framework? Seeking guidance on performing CRUD operations with NodeJs, Javascript, and Postgres sans ExpressJS. G ...

Is it time to set up your own MySQL Database?

let connection = mysql.createConnection({ user: 'root', password: '1234', database: 'data101', port: 3306 }); While using the MySQL package for NodeJS to create a database, I have a question. Do I need to manually cr ...

ajax response includes both a single variable as well as an array variable

My comment form requests newtimestamp and newcomment variables. The newtimestamp is a single variable, while the newcomment is an array generated from a foreach loop. A snippet from ajaxrequest.php: foreach ($array2 as $print2) { $var1 = $print2['va ...

What is the best way to store various types of functions within a single object key?

I have a dilemma where I am storing values and individual typed functions in an array of objects. Whenever I loop through the array, all the types of all typed functions in the array are required for any value. How can I make this more specific? Check it ...

Transfer elements from collections employing multer

Data Payload Example:- education[0][university]: jru education[0][degree]: mca education[0][specialization]: computer application education[0][certificate_pdf_url]: (binary) education[0][degree_type]: Teaching Degree education[0][years_of_study]: [&q ...

Issue with Paypal Express Checkout page appearance in Firefox browser

After completing the integration of PayPal Express Checkout on my client's website, I encountered an issue while testing its features and checking for browser compatibility. When going through the checkout process in Firefox, the PayPal Checkout Page ...

The v-model for a particular field is not reflecting real-time updates like the other fields with the same datatype. I'm trying to figure out what could be causing this issue

In my specific model, there are various values that can be updated through a form on the webpage. These values include "Quantity", "Rate", "Amount", "Net rate", and more. The problem I am facing is with binding these values with my inputs using v-model. E ...

When the session times out, Ajax mistakenly displays the login page instead of an error message

I have a question that is somewhat similar to this one, but I will explain my understanding of the situation and the ideas I have come up with to fix it. Hopefully, someone can guide me in the right direction. The scenario: In my webapp, an authenticated ...

Is there a way to create a bar chart that begins at the 0 point of the y-axis instead of starting from the base of the SVG?

Is there a way to start the bar chart from the 0 point of the y-axis instead of the very bottom of the svg? How can I achieve this? let url = "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json"; const padding = 5 ...

What are some ways to customize the appearance of Skype for Business HTML messages when integrating with the Bot Framework?

Recently, I created a bot using Microsoft's bot framework and I've noticed that while it supports sending HTML messages, the CSS styling doesn't seem to work. As a result, the HTML messages appear quite bland and I'm really eager to add ...

What is the best way to switch to a new HTML page without causing a page refresh or altering the URL?

Is there a way to dynamically load an HTML page without refreshing the page or altering its URL? For instance, if I am currently on the http://localhost/sample/home page and I want to switch to the contact us section by clicking on a link, is it possible t ...

The ul cannot be hidden if there are no li elements within it

Currently, I am attempting to hide the unordered list (ul) on a specific page using AJAX due to certain sections of the site being Ajax-based. <ul class="sub-nav-20-m" id="filtersList_m"> </ul> Below is the code that I hav ...

Mastering the art of flawlessly executing kerning-generated code

I am facing a problem while implementing logotext with kerning technique in the <header> element. I found a useful tool made by Mr. Andrew which can be accessed through this link. Before making any modifications, I had the following code in the heade ...

Check the value of a single bit in JavaScript: Is the bit on (1) or off (0)?

Is there a way in JavaScript to determine if a single Bit is On (1) or Off (0)? function isBitOn(number, index) { // ... ? } // Example: let num = 13; // 1101 isBitOn(num, 0); // true 1 isBitOn(num, 1); // false 0 isBitOn(num, 2); // true 1 isBit ...

Issue with child div exceeding 100% height within CSS Flexbox causing inconsistency in Firefox and Chrome browsers

I am facing a challenge trying to make a div resize to match its parent's height using flexbox. This issue seems to occur only in Chrome (48), as it displays correctly in Firefox (44). You can view the example on Fiddle: https://jsfiddle.net/jvilla/k ...

Dynamic Rendering and Retrieving Component HTML in Angular

Generate the HTML code of a component to open a new tab with an about:blank page. Reason: This method helps avoid creating HTML using string variables, such as: var html = '<div> <h3>My Template</h3> &a ...

Struggling to pinpoint the specific value in the getjson response

When using my getjson code, I noticed that it logs successfully when I provide the correct data.value. However, if I input invalid data.value, it displays an empty array[] on the browser. How can I modify my getjson code to identify when the json returns ...

Opencart now offers a feature that allows for instant quantity updates in your cart

When using standard opencart functionality, users typically have to manually click the update button after adding a product to their cart in order to update the quantity. To see an example of this behavior, visit . However, I would like the cart informatio ...