Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap btn-group button deactivates when clicking away

I'm working with Bootstrap v3 and I'm using the button group feature as a means of choosing between 3 categories. One of these categories should also be pre-selected upon the page loading. However, whenever I click away from the selected button, it is deactivated.

This is normal if I'm clicking another button, but the selected button deactivates if I click anywhere outside of it. Also, the button I preactivate with the "active" class remains active regardless of if I select other buttons.

Is there a way I can get these buttons to behave like a group of radio buttons that will keep their state even when I click away from them and they lose focus?

Here's the code I'm currently working with:

<div class="btn-group btn-group-justified">
    <div class="btn-group">
        <button type="button" class="btn btn-default active"><span class="goods">Good</span></button>
    </div>
    <div class="btn-group">
        <button type="button" class="btn btn-default"><span class="services">Service</span></button>
    </div>
    <div class="btn-group">
        <button type="button" class="btn btn-default"><span class="spaces">Space</span></button>
    </div>
</div>

Edit: Heres a link to jsfiddle displaying my issue: http://jsfiddle.net/7JT6M/

like image 250
terpak Avatar asked Jul 17 '14 05:07

terpak


1 Answers

You need javascript logic to maintain the state.

$(".type").click(function(){
   $(".type").removeClass("active");
   $(this).addClass("active");
});

<div class="btn-group btn-group-justified">
    <div class="btn-group">
        <button type="button" class="btn btn-default type active"><span class="goods">Good</span></button>
    </div>
    <div class="btn-group">
        <button type="button" class="btn btn-default type"><span class="services">Service</span></button>
    </div>
    <div class="btn-group">
        <button type="button" class="btn btn-default type"><span class="spaces">Space</span></button>
    </div>
</div>

DEMO

like image 82
Yuliam Chandra Avatar answered Sep 23 '22 22:09

Yuliam Chandra