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?