What is the best way to disable form inputs with the click of a radio button?

My goal is to have two radio buttons functioning in a way that when the first radio button "Main address" is checked, the form below should be disabled. However, if I check the second radio button "Other address", the form should become activated.

In addition, I want the form to start off being disabled by default if neither of the radio buttons are checked (when initially arriving on the page, both radio buttons are unchecked).

I am looking for a solution to implement this functionality using JavaScript.

https://i.sstatic.net/KBDsi.png

<form class="needs-validation" novalidate>
                        <!--was-validated -->
                        <div class="d-block my-3">
                            <div class="custom-control custom-radio">
                                <input id="Main address" name="paymentMethod" type="radio" class="custom-control-input" required>
                                <label class="custom-control-label" for="Main address">Main address</label>
                            </div>
                            <div class="custom-control custom-radio">
                                <input id="Other address" name="paymentMethod" type="radio" class="custom-control-input" required>
                                <label class="custom-control-label" for="Other address">Other address</label>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="cc-name">Address</label>
                                <input type="text" class="form-control" id="cc-name" placeholder="" required>
                                <small class="text-muted">Please enter your other address.</small>
                                <div class="invalid-feedback">
                                    Name on card is required
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <label for="cc-expiration">City</label>
                                <input type="text" class="form-control" id="cc-expiration" placeholder="" required>
                                <div class="invalid-feedback">
                                    Expiration date required
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <label for="cc-cvv">Postcode</label>
                                <input type="text" class="form-control" id="cc-cvv" placeholder="" required>
                                <div class="invalid-feedback">
                                    Security code required
                                </div>
                            </div>
                        </div>
                        <hr class="mb-4">
                        <button class="btn btn-primary btn-lg btn-block" href="index.php" type="submit">Continue to checkout</button>
                    </form>

Answer №1

To make the address-DIV hidden or visible based on radio button selection, add an event listener to each radiobutton. When Main_address is clicked, add the 'hide' class to hide the address-DIV. Conversely, when Other_address is clicked, remove the 'hide' class to show the address-DIV again.
Avoid using an id with a space in it as it may cause issues; therefore, I have updated the ids for radios accordingly.

let mainAdress= document.getElementById("Main_address");
mainAdress.addEventListener('click', function() {
    document.getElementById("address").classList.add('hide');
});

let otherAdress= document.getElementById("Other_address");
otherAdress.addEventListener('click', function() {
    document.getElementById("address").classList.remove('hide');
});
.hide { visibility: hidden; }
<form class="needs-validation" novalidate>
  <!--was-validated -->
  <div class="d-block my-3">
    <div class="custom-control custom-radio">
      <input id="Main_address" name="paymentMethod" type="radio" class="custom-control-input" required>
      <label class="custom-control-label" for="Main address">Main address</label>
    </div>
    <div class="custom-control custom-radio">
      <input id="Other_address" name="paymentMethod" type="radio" class="custom-control-input" required>
      <label class="custom-control-label" for="Other address">Other address</label>
    </div>
  </div>
  <div class="row" id ='address'>
    <div class="col-md-6 mb-3">
      <label for="cc-name">Address</label>
      <input type="text" class="form-control" id="cc-name" placeholder="" required>
      <small class="text-muted">Please enter your other address.</small>
      <div class="invalid-feedback">
        Name on card is required
      </div>
    </div>
    <div class="col-md-3 mb-3">
      <label for="cc-expiration">City</label>
      <input type="text" class="form-control" id="cc-expiration" placeholder="" required>
      <div class="invalid-feedback">
        Expiration date required
      </div>
    </div>
    <div class="col-md-3 mb-3">
      <label for="cc-cvv">Postcode</label>
      <input type="text" class="form-control" id="cc-cvv" placeholder="" required>
      <div class="invalid-feedback">
        Security code required
      </div>
    </div>
  </div>
  <hr class="mb-4">
  <button class="btn btn-primary btn-lg btn-block" href="index.php" type="submit">Continue to checkout</button>
</form>

Answer №2

Here's a potential solution that could be effective:

radioButton.onchange = function() {
    input.disabled = (radioButton.value === 'on') ? true : false;
}

Answer №3

An alternative approach could be to have the additional address inputs initially disabled, only enabling them when the corresponding radio button is selected. This way, the extra address fields are hidden until they are needed.

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

Revise Bootstrap accordion setup

I currently have a Bootstrap accordion set up on my website using Bootstrap 4.1.0 <div id="accordion" class="mt-3"> <div class="card"> <div class="card-header bg-dark text-white" id="headingOne"> <h5 class="mb-0 f ...

Verify the presence of a JSON object within the session storage using JavaScript

I'm currently developing a website where some data is stored within the session. In the initial page, I need to verify if the JSON object already exists in the session. Below is the code snippet that's causing issues: var passedTotal = JSON.par ...

One of the quirks of Angularjs is that the ng-enter animation will only be

The initial animation only occurs the first time. I am utilizing Angularjs version 1.2.22 Here is the CSS that I am using : .ng-enter { animation: bounceInUp 2s; } .ng-leave { animation: bounceOutUp 2s; } And this is the route configuration : ...

The error message "item is not defined in nodejs" indicates that the variable

I am facing an issue while trying to retrieve data from a JSON file using Node.js and Express. I have defined the methods with exports, but I keep getting errors in my browser. I am unsure why it is not functioning correctly, as I have specified the metho ...

I keep receiving a warning from React-Router stating that it is not possible to modify the <Router routes> component

In my application, I am utilizing React-Router along with a customized history object. The setup looks something like this: import { createHistory } from 'history'; import { Router, Route, IndexRedirect, useRouterHistory } from 'react-rout ...

Encountering issues when implementing react-router with the client-side library

After following the author's suggestion, I've successfully loaded the client-side library. The recommended method is to simply drop a <script> tag in your page and use the UMD/global build hosted on cdnjs. I have ensured that ReactRouter i ...

I'm curious if it's possible to create a scrolling marquee on an SVG path with the use of HTML and CSS?

I am interested in creating a unique effect similar to what is showcased on this website or in the main menu of Colin McRae Rally 2.0. My goal is to generate a path and animate text along it, with the letters wrapping around to the start as they reach the ...

JavaScript Time and Amount Formatting

My issue involves the formatting of returned data. I am looking to compile all values into a list with adjustments made to the time format and fare amount as indicated. Specifically, I need to remove commas from fare amounts and AM/PM from departure and ar ...

Tips for correctly deciphering a JSON string that has been encoded using Html.Raw(Json.Encode(Model)):

Encoding model data into an HTML element can be done like this: @Html.Raw(Json.Encode(Model)); The resulting JSON string appears as follows: {"TestList":[{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6144","SeqNo":9306,"SeqNoSpecified":true,"TSeqNo ...

Utilize the assigned value of a variable from a separate file

Is it possible to set a variable in an external file called "Variable.js", assign it a value in a file named "Page1.html", and then use that variable with its assigned value in another file named "Page2.html"? For example, let's consider the contents ...

Sound feature malfunctioning in Internet Explorer 8

Currently, I am working on a SharePoint page and facing an issue with displaying an audio file in IE8. Initially, it was working fine but now it is not showing up at all. Interestingly, the audio file plays perfectly in Chrome. Do any of you have alternati ...

Issue: Unable to navigate the dependency graph: Module '@badeball/cypress-cucumber-preprocessor/steps' cannot be located

Encountering an error when running my feature file and unsure of the issue. See screenshots below: https://i.sstatic.net/Ks5Sy.png https://i.sstatic.net/BP4rl.png https://i.sstatic.net/8IoMM.png ...

Error message "Module not found in Vue" occurs when changing image URL to an online image

I am currently working on a dynamic image display feature where I retrieve image names as strings from a backend. To manage a large number of images, I plan to store them online while maintaining the same logic for displaying them. Previously, I achieved t ...

Numerous AJAX requests consolidated into a single file

Here is my HTML code snippet: <div class="a1"></div> <div class="a2"></div> <div class="a3"></div> <div class="a4"></div> <div class="a5"></div> I am looking to make an AJAX request in the follo ...

Replicate the drop file event

Can the drop event be simulated or faked using only JavaScript? How can this type of event be tested? Consider a drag-and-drop upload example like this one on this page. Is it possible to trigger the "drop" event with a file without actually dropping a fi ...

Ensure that the pop-up text triggered by a button click is contained within the same webpage

Allow me to preface my inquiry by mentioning that I possess very minimal coding knowledge, so please bear with any technical terminology inaccuracies. I currently have a webpage featuring various questions, each accompanied by a button below. Upon clickin ...

Did I incorrectly pass headers in SWR?

After taking a break from coding for some time, I'm back to help a friend with a website creation project. However, diving straight into the work, I've encountered an issue with SWR. Challenge The problem I'm facing is related to sending an ...

Postman is showing a 404 error message when trying to access an Express JS route that uses a POST request

Currently, I am working on creating APIs in Node.js with express and body-parser. While GET requests work fine using Postman, there seems to be an issue with POST requests as it consistently throws a 404 error saying Cannot GET / Express Version: @4.17.1 ...

Ways to resolve issues related to null type checking in TypeScript

I am encountering an issue with a property that can be null in my code. Even though I check for the value not being null and being an array before adding a new value to it, the type checker still considers the value as potentially null. Can anyone shed lig ...

Node.js unable to verify RSA-PSS signature due to validation issues

I currently have a JavaScript client and a Node.JS server setup. My goal is to sign a basic text on the client side, send the signature along with the publicKey to the server, and have the server verify the publicKey. Everything seems to work fine on the ...