Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap button group pre-select button with html only

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>
like image 377
whatdoesitallmean Avatar asked Mar 21 '23 06:03

whatdoesitallmean


1 Answers

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>
like image 191
Josh Crozier Avatar answered Apr 01 '23 22:04

Josh Crozier