Bootstrap 5 comes with that feature already, you can read more about that on this section of the docs: https://getbootstrap.com/docs/5.0/components/button-group/#checkbox-and-radio-button-groups
let radios = document.querySelectorAll('.btn-group.btn-group-unselectable input[type="radio"]');
radios.forEach(radio => {
radio.addEventListener('click', function(e) {
if (this.getAttribute('data-previous-value') == 'true') {
e.target.checked = false;
} else {
radios.forEach(radio => {radio.setAttribute('data-previous-value', false)});
}
this.setAttribute('data-previous-value', e.target.checked);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group btn-group-unselectable" role="group" aria-label="Basic radio toggle button group">
<input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off" checked>
<label class="btn btn-outline-primary" for="btnradio1">T</label>
<input type="radio" class="btn-check" name="btnradio" id="btnradio2" autocomplete="off">
<label class="btn btn-outline-primary" for="btnradio2">E</label>
<input type="radio" class="btn-check" name="btnradio" id="btnradio3" autocomplete="off">
<label class="btn btn-outline-primary" for="btnradio3">M</label>
<input type="radio" class="btn-check" name="btnradio" id="btnradio4" autocomplete="off">
<label class="btn btn-outline-primary" for="btnradio4">L</label>
</div>
EDIT
You can do this with some JavaScript code, you need to store a temp value on the element when click on radio buttons because every time you click on the radio it is set to checked, so we need to know the previous state of the checked attribute so when we click again we can know if the button is checked
(active), if it is, we set to checked = false
.
Also, i added the class .btn-group-unselectable
to .btn-group
element.
Here is the JQuery version of this code:
$('.btn-group.btn-group-unselectable input[type="radio"]').click(function(e) {
if($(this).attr('data-previous-value') == 'true'){
e.target.checked = false
} else {
$('input[type="radio"]').attr('data-previous-value', false);
}
$(this).attr('data-previous-value', e.target.checked);
});