Issue
When I have a Bootstrap 5 button group, the code looks as follows:
<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>
This works fine if the group is on the page during pageload. However, if I dynamically append the elements after pageload, the buttons stay "active" once clicked and don't toggle properly.
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>
Any idea why this might be?
Solution
You need the dynamically added buttons to share a name attribute.
If you notice in your onload group they all have the same name attribute: name="btnradio"
Whereas in your dynamically added group, they all have different name attributes: button.name = type;
Since they all have different names, they're seen as different button groups, so selecting another won't deselect the others.
Answered By - Ajschuit
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.