2

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());
                    });
RonaDona
  • 912
  • 6
  • 13
  • 30

1 Answers1

2

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>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
  • gaetano@ when I do this, alert($('.btn-group > .btn.active').text()); does not give a value anymore. It gives an empty string. – RonaDona Sep 17 '16 at 12:52
  • @RonaDona: Now I added the feature: if you click again on the same button the state change from active to not active. This in order to give you the possibility to deselect the button itself. Let me know if this time it works like you want. Thanks again – gaetanoM Sep 17 '16 at 13:30
  • 1
    @RonaDona I'm glad for you. – gaetanoM Sep 17 '16 at 13:31
  • 1
    This solved my issue too after researching for an hour! Thanks! – lily Jun 08 '17 at 10:13