Ranjith Ranjith - 7 months ago 37
Javascript Question

jQuery set active class for button select

I have some html stuffs like this,

<div class="btn-group" role="group">
<button type="button" class="btn btn-default">Low Cost/Effeciency</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default">Average</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default">High Cost</button>
</div>


From my above snippets, each
btn-group
contains one
button
. I want to add
active
class when
button
click and remove
active
class which is the button already set as
active
. It means like radio button selection.

I tried like this in jQuery, but doesn't provide exact solutions.

$(document).on('click', '.btn-group button', function (e) {
$(this).addClass('active').parent('.btn-group').find('button').removeClass('active');
});


How can I achieve this?

Answer

You can use toggleClass for doing that,

$(document).on('click', '.btn-group button', function (e) {
    $(this).toggleClass('active');
});

DEMO

Edit:

$(document).on('click', '.btn-group button', function (e) {
    $(".active").not($(this).addClass('active')).removeClass();
});

DEMO