Issues with Radio Button Functionality in Bootstrap 5 when Integrated with JS Validation

Here is the JavaScript code I created:

let radioChange = document.getElementsByName("pain-location");
let headPain = document.getElementById("headPain");
let shoulderPain = document.getElementById("shoulderPain");
let backPain = document.getElementById("backPain");
let listInner = document.getElementsByClassName("list-inner");

radioChange[0].addEventListener('click', (e) => {
if(document.getElementById('painOption1').checked) {
    for (let i=0;i<listInner.length;i+=1){
        listInner[i].style.display = 'none';
    }
    headPain.style.display = "block";
} else if(document.getElementById('painOption2').checked) {
    for (let i=0;i<listInner.length;i+=1){
        listInner[i].style.display = 'none';
    }
    shoulderPain.style.display = "block";
} else if(document.getElementById('painOption3').checked) {
    for (let i=0;i<listInner.length;i+=1){
        listInner[i].style.display = 'none';
    }
    backPain.style.display = "block";
}
});

And here is the corresponding HTML:

<div class="btn-group man-points">
                <div class="ptn-check-point" id="optionBtn1">
                    <input type="radio" class="btn-check" name="pain-location" id="painOption1" required>
                    <label class="btn btn-secondary" for="painOption1"></label>
                </div>
                <div class="ptn-check-point" id="optionBtn2">
                    <input type="radio" class="btn-check" name="pain-location" id="painOption2" checked required>
                    <label class="btn btn-secondary" for="painOption2"></label>
                </div>
                <div class="ptn-check-point" id="optionBtn3">
                    <input type="radio" class="btn-check" name="pain-location" id="painOption3" required>
                    <label class="btn btn-secondary" for="painOption3"></label>
                </div>
            </div>

            <div class="list-inner" id="headPain">
                <h5>Head</h5>
            </div>
            <div class="list-inner" id="shoulderPain">
                <h5>Shoulder</h5>
            </div>
            <div class="list-inner" id="backPain">
                <h5>Shoulder</h5>
            </div>

I implemented this using Bootstrap 5. The JS code changes elements to be displayed based on a radio button selection.

Answer №1

Make sure to check this out - the event listener is now added to all radio fields by looping through each one, rather than just the first.

        let headPain = document.getElementById("headPain");
        let shoulderPain = document.getElementById("shoulderPain");
        let backPain = document.getElementById("backPain");
        let listInner = document.getElementsByClassName("list-inner");
        document.querySelectorAll('input[name="pain-location"]').forEach(element => {

            element.addEventListener('click', (e) => {
                if (document.getElementById('painOption1').checked) {
                    for (let i = 0; i < listInner.length; i += 1) {
                        listInner[i].style.display = 'none';
                    }
                    headPain.style.display = "block";
                } else if (document.getElementById('painOption2').checked) {
                    for (let i = 0; i < listInner.length; i += 1) {
                        listInner[i].style.display = 'none';
                    }
                    shoulderPain.style.display = "block";
                } else if (document.getElementById('painOption3').checked) {
                    for (let i = 0; i < listInner.length; i += 1) {
                        listInner[i].style.display = 'none';
                    }
                    backPain.style.display = "block";
                }
            });
        })

source: How to use on addEventListener on radio button in Plain Javascript?

Acknowledgment:

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 am currently exploring options on how to eliminate the excess space at the top of the screen when viewing on smaller devices like mobile phones and tablets

Utilizing bootstrap for my layout, I have a row with 4 columns where the content within each div has varied top margins. This creates a cascading effect and looks great on desktop screens. However, the issue arises when viewing it on smaller screens as the ...

Implementing Materialize CSS functionality for deleting chips

I've been attempting to extract the tag of a deleted chip from the div within the Materialize chips class, but I'm hitting roadblocks. My failed attempts so far: $('.chips').on('chip.delete', function(e, chip){ console.lo ...

Deliver dynamic JavaScript files using Node.js

Query: Is there a way to serve a JavaScript file dynamically, where certain variables can be changed based on parameters passed in the URL? I'm looking for a solution similar to using an HTML Jade template but for pure JavaScript. Situation: Imagin ...

Employing a pair of interdependent v-select components to prevent any duplicate entries

I am currently working with two v-select boxes that share similar data. In my scenario, I extract attachments from an email and load them into an array. The issue I encountered is that the first select box should only allow the selection of one document, w ...

Debug errors occur when binding to computed getters in Angular 2

Currently, I am integrating Angular 2 with lodash in my project. Within my model, I have Relations and a specific getter implemented as follows: get relationsPerType() { return _(this.Relations) .groupBy(p => p.Type) .toPairs() ...

When you click, apply the hidden class to all the div elements

Is there a way to apply the .hide class to all .slide divs whenever the .option button is clicked? If so, how can I modify my JavaScript code so that all .slide divs receive the .hide class (if they don't already have it) upon clicking the .option bu ...

Load jQuery DataTable when the event changes

I have implemented a script that loads the DataTable when the page is ready: function initializeDataTable(serviceUrl) { var $dataTable = $('#example1').DataTable({ "ajax": serviceUrl, "iDisplayLength": 25, "order": [[2, "asc"]], ...

Exploring Event Listeners in the World of JavaScript and/or jQuery

Is there a more sophisticated way to monitor the execution of a specific function in JavaScript or jQuery? Instead of waiting for an event like $('#mything').click(function(){ //blah }), I prefer to be notified when a particular function is trig ...

Warning: React JS encountered errors with propType validation and uncontrolled input handling

I've been encountering challenges with React JS and trying to enhance the todoList after completing a crash course. Despite spending 8 hours troubleshooting, I'm still struggling. Hopefully, seeking assistance here will provide me with a fresh pe ...

Gradually appear with jQuery while maintaining current position

Exploring Display Options In my current setup, I have text that initially has a display:none property, and jQuery is applied to fadeIn() the content. The challenge lies in the fact that since the text is centered, as each word appears, the positioning on ...

Dynamically parallelizing functions with async and arrays

I have recently integrated the fantastic "async" module by caolan into my Node.js project: Below is a snippet of the code in question: exports.manageComments = function(req, res) { var toDeleteIds = []; var deleteFunctions = []; if (req.body. ...

Converting a basic XMLHttpRequest or XDomainRequest into a custom-made jQuery Deferred object

Can a raw XMLHttpRequest or XDomainRequest be converted into a jQuery Deferred object (or encapsulated within one)? By "raw", I mean the object is instantiated directly using new XMLHttpRequest() or new XDomainRequest(), rather than utilizing jQuery' ...

Unable to display Three.JS OBJ Model

I am facing an issue with loading a .obj model in Three.js. I created the model in Cinema 4D, exported it with a scale of 1 meter, and tried to load it using OBJLoader in Three.js. However, even though there are no errors, the model is not showing up. Wh ...

Can a Promise be added to an Array later using Promise.all()?

While diving into a project, I pondered whether it is possible to initiate the Promise.all function in JavaScript and have it continue adding more Promises to the array while also running the existing ones. Quite an intriguing question! ...

Find the disparity between values within an object and an array

Given the object and array of numbers below, how can I identify which number in the array is not represented as an ID in the object? In this case, the missing number is 1453. [ {id: 60, itemName: 'Main Location - 1100 Superior Road - Cleveland' ...

Calling a JavaScript function from server-side code (without using startup scripts)

In essence, my objective is as follows: Initiate deletion of a record upon button click. Delete the record only if a specific column (Location) is null (working perfectly). If the specific column is not null, prompt the user for confirmation before proce ...

Issue with Socket IO: It does not function properly with public IP addresses, but it works perfectly on localhost

I've been working with socket io and have successfully deployed the app on my localhost. For client-side connection, I'm using : var socket = io.connect(window.location.origin + ":3333"); To ensure scalability, on the server side I am utilizin ...

Troubleshooting 404 errors with Cordova, AngularJS, and Node.js (Express) when using $http with

I'm currently testing in an Android environment using Cordova, AngularJS, and Node.js (Express). I'm attempting to retrieve some data using $http(), but consistently encountering a 404 error message (as seen in the alert below). Here's the ...

Methods to verify if an array contains a particular string within a PUG template

I'm currently working with NodeJS using Express and the PUG view engine. My goal is to determine whether an array includes a specific string. I've experimented with JavaScript's built-in methods like: array.includes(str) array.indexOf(str) ...

What is the method for including a placeholder with sequential numbering?

When I click on the "Add String" button, it clones the first table row with an input in the table and adds it to the table. I also need to add a +1 number in the placeholder of the copied element. How can I determine the last placeholder before copying and ...