RonaDona RonaDona - 2 months ago 10
jQuery Question

Bootstrap ButtonGroup Select 1 Button Only

I am using Boostrap 3.3.7 and are trying to use Buttons as 'Radio Button'.

This is the HTML:

<div id="selector" class="btn-group" data-toggle="buttons-radio">
<button name="resolution" class="btn btn-default btn-sm">
720
</button>
<button name="resolution" class="btn btn-default btn-sm">
480
</button>
<button name="resolution" class="btn btn-default btn-sm">
360
</button>
</div>


When I select one button, then select another one, the first does not get deselected. I tried to deselect it with JQuery but it did not work:

$('.btn-group > .btn').removeClass('active')
$('.btn-group > .btn').eq(0).addClass('active')


How can I make sure I keep one selected only? My objective is to have one button selected so I could use it. Something like this:

$("#submitButton").click(function () {
alert($('.btn-group > .btn.active').text());
});

Answer

In order to maintain active the current button you may delegate the click event to avoid the event propagation and buttons change state.

So the snippet is:

$(document).on('click', '[name="resolution"]', function(e) {
  e.stopPropagation();
  
  // add class active to current button and remove it from the siblings
  $(this).toggleClass('active')
        .siblings().not(this).removeClass('active');
})


// for test purposes
$(function () {
  $('#myBtn').on('click', function(e) {
    console.log('Active button: ' + $('.btn-group > .btn.active').text());
  })
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id="selector" class="btn-group" data-toggle="buttons-radio">
    <button name="resolution" class="btn btn-default btn-sm">
        720
    </button>
    <button name="resolution" class="btn btn-default btn-sm">
        480
    </button>
    <button name="resolution" class="btn btn-default btn-sm">
        360
    </button>
</div>
<button id="myBtn" class="btn">Click Me To debug</button>