Troubleshooting Issue with Bootstrap Button Group Failing to Properly De-Select Dynamically Appended Buttons

My experience with a Bootstrap 5 button group is that the code appears as shown below:

<div class="btn-group d-flex justify-content-between m-4">
  <input id="a" type="radio" class="btn-check" name="btnradio" autocomplete="off">
  <label class="btn btn-outline-primary" for="a">Option A</label>
  <input id="b" type="radio" class="btn-check" name="btnradio" autocomplete="off">
  <label class="btn btn-outline-primary" for="b">Option B</label>
  <input id="c" type="radio" class="btn-check" name="btnradio" autocomplete="off">
  <label class="btn btn-outline-primary" for="c">Option C</label>
</div>

While this structure works perfectly when the group is initially loaded on the page, I encountered issues when attempting to append the elements dynamically after the page had already loaded. In this scenario, the buttons remained in an "active" state after being clicked and did not toggle correctly.

let options = ["D", "E", "F"];

let group = document.createElement('div');
group.className = 'btn-group d-flex justify-content-between m-4';
for (let type of options) {
  let button = document.createElement('input');
  button.id = type;
  button.name = type;
  button.type = 'radio';
  button.className = 'btn-check';
  button.autocomplete = 'off';
  group.append(button);
  let label = document.createElement('label');
  label.htmlFor = type;
  label.className = 'btn btn-outline-primary';
  label.innerHTML = 'Option ' + type;
  group.append(label);
}
document.body.append(group);
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5/dist/css/bootstrap.min.css" />
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
  <h1 class="m-4">On Pageload</h1>
  <div class="btn-group d-flex justify-content-between m-4">
    <input id="a" type="radio" class="btn-check" name="btnradio" autocomplete="off">
    <label class="btn btn-outline-primary" for="a">Option A</label>
    <input id="b" type="radio" class="btn-check" name="btnradio" autocomplete="off">
    <label class="btn btn-outline-primary" for="b">Option B</label>
    <input id="c" type="radio" class="btn-check" name="btnradio" autocomplete="off">
    <label class="btn btn-outline-primary" for="c">Option C</label>
  </div>
  <h1 class="m-4">Dynamically Appended</h1>
</body>
</html>

Have any insights on why this behavior occurs?

Answer №1

To ensure proper functionality, it is important for the dynamically added buttons to have a shared name attribute.

Upon inspection of your onload group, you will notice that they all share the same name attribute: name="btnradio"

In contrast, the dynamically added group contains buttons with different name attributes: button.name = type; https://i.sstatic.net/wBYur.png

Having different names for each button results in them being perceived as separate button groups, preventing the deselection of others when a new one is selected.

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

How to send arrays through JSON?

I have some PHP code: $ids = array(1,2,3); $names = array("cat","elephant","cow"); $originalSettings = array ('ids'=>$ids,'names'=>$names); $jsonSettings = json_encode($originalSettings); echo $jsonSettings; Here ...

An AngularJS Dilemma: Troubleshooting JSON Integration

I am working with a JSON source and trying to fetch results from it using a post request. Interestingly, when I use the POSTMAN extension in Chrome, everything works perfectly fine. However, when I try the same thing with AngularJS, the page keeps loading ...

How can I use XPATH to target a div after choosing a nested element?

I had the task of creating a universal identifier to locate a dropdown menu following a label. There are 10 different forms, each with a unique structure but consistent format, which means I cannot rely on specific IDs or names. Instead, my approach was to ...

Unable to convert cursor to jpg format

I am facing an issue where I have a jpg file stored in the same folder as my styles.css, and I want to change the cursor on a webpage to this particular jpg file. Despite my efforts, it seems like the cursor is not changing as expected. Currently, I am us ...

Creating an XPATH Selector with SCRAPY

Having trouble retrieving the product name from a webpage: Struggling to locate XPATH that delivers a useful, specific result. Apologies for my initial question being quite basic :( class V12Spider(scrapy.Spider): name = 'v12' start_ur ...

Tips for optimizing character count for mobile web pages with varying screen sizes and font settings

As I embark on developing an eBook mobile app, I am faced with various considerations such as screen size, font size, and determining the number of paragraphs to include on a single page based on the current screen and font settings. My aim is to adjust t ...

What is the method to update a div containing the video title when a user clicks on a related video?

How can I make a div update with the title of the currently playing video when a user clicks on another video? I am having trouble finding an event in the API that lets me know when the video source has changed. Is there a specific event I should be listen ...

Left-floating div moves to the bottom

My CSS is set up to float my divs next to each other, creating 3 rows and 3 columns as needed. However, I'm facing an issue where the first div in the second row is being pushed under the second column instead of the first one. It's quite puzzlin ...

Angular, JavaScript, and PHP are three powerful programming languages that

This file contains HTML code <ul class="list"> <li id="numword" data-score="{{item.score}}" class="" ng-repeat="item in words track by $index"> {{item.word}} {{item.score}} </li> </ul> Here is the visual representa ...

What is the best way to find the longest element with the same class name using jQuery?

How can I dynamically find elements with the same length of class names? var className = $('.floor-4').attr('class').split(' ')[1]; var classLength = $('.' + className).length; Here is the HTML code: <div id="d ...

When iterating through a table, an error occurs stating that the property "rows" is not available on type HTMLElement (

Issue Error TS2339 - Property 'rows' does not exist on type HTMLElement when looping through table in Angular 7 Encountering error when trying to loop through HTML table in Angular 7 Currently working with Angular 7 and facing an error while ...

Sending JavaScript functions to PHP files via Ajax

My Current Project: I am currently developing a script that provides users with choices and generates new options based on their selections. To achieve this, I have created two scripts - one for the HTML structure of my page and another for fetching serve ...

What is the best way to extend the width of an element within a Bootstrap column beyond the column itself?

Apologies for any language errors, but I have a query regarding Bootstrap. I am currently working on making a website responsive and I have a row with 4 columns set up like this: The "seeMore" div is initially hidden and on clicking the boxToggle element ...

What is the best way to identify duplicate keys in fixed JavaScript objects?

My approach so far has been the following: try { var obj = {"name":"n","name":"v"}; console.log(obj); // outputs { name: 'v' } } catch (e) { console.log(e); // no exceptions printed } My goal is to detect duplicate keys within a ...

Tips for concealing a Bootstrap modal during the show.bs.modal event

Check out this code snippet: let order_modal = document.getElementById('order'); order_modal.addEventListener('show.bs.modal', function (e) { bootstrap.Modal.getInstance(order_modal).hide(); }, false); Upon opening the modal, the ...

Text that fades in and out based on scrolling past a specific point

There's a text containing <p> and <h1>. The text finishes with one <h1>. I'm looking to speed up the Y translation of the <p> twice when I reach the bottom of the document (where the last h1 is located in the middle of th ...

How can I retrieve the date from the following week with Ionic?

I am looking to retrieve the date of today plus 7 days. Currently, I am retrieving today's date using the following code: public dateToday: string = new Date().toLocaleDateString('de-DE'); After searching on Google, I came across the soluti ...

Implement a cron job in Node.js to automatically trigger an Express route on a weekly basis

I need to run tests on a certain page every week by creating a cron job that will access my express route at regular intervals. Currently, I have set up a cron job to run every 2 minutes as a test: //schedule job every 2 minutes schedule.scheduleJob("* /2 ...

HTML5 - Adding Space to Main Section with a Two-column Layout

After spending 3 and a half hours racking my brain, I still can't figure out how to complete two seemingly simple tasks. First, I need to pad the outside of paragraph div, and secondly, I want to split the main section into two columns to add some lin ...

The image code is not recognizing the image source

In my attempt to dynamically set the image source in an HTML element after creating it with JavaScript, I have made some interesting observations through testing and alert messages: When providing the image src as a fixed filepath during the creation o ...