Using Bootstrap I want a button group but with one button preselected. If I use the html below then the first button gets preselected, but it remains active even when I click on one of the other buttons.
Using only html how can I define the button group with one button selected where that button will deselect when I click on one of the other buttons.
<div class="btn-group">
<button type="button" class="btn btn-default active">Left</button>
<button type="button" class="btn btn-default">Middle</button>
<button type="button" class="btn btn-default">Right</button>
</div>
It's not completely possible to do this with HTML only - (as your title implies).
Really, the only thing you could do without JavaScript is add the attribute autofocus="autofocus"
to the desired element like this:
<button type="button" class="btn btn-default" autofocus="autofocus">Left</button>
As the attribute implies, the button will automatically be focused in supported browsers. If another button is clicked, the focus of the first button will be removed.
EXAMPLE HERE
It's worth noting that the styling of .btn-default.active
is the same as .btn-default:focus
:
.btn-default:focus, .btn-default.active {
color: #333;
background-color: #ebebeb;
border-color: #adadad;
}
Unfortunately, the focus will also be removed when clicking anywhere else on the page too. If this is a problem, JavaScript would be needed to solve this. The solution would be to have the active
class on the desired element and then remove it when clicking on any of the sibling button elements. The selection would be mutually exclusive like with radio elements.
Here is an example taken directly from the Bootstrap JS documentation. It's worth noting that the Bootstrap JS file/jQuery need to be included.
EXAMPLE HERE
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1"> Option 1
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2"> Option 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3"> Option 3
</label>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With