Reputation: 4755
I'm actually using this button group structure with bootstrap. Now I need to add class active to each button when I click on it. And remove from it when I click on another button.
This is my HTML structure, is something like that:
<body>
<div id="header">
<div class="logo">Prova<span class="sec-logo">toscana</span>15</div>
<div class="bottoni">
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default" id="b1">12345</button>
<button type="button" class="btn btn-default" id="b2">12345</button>
<button type="button" class="btn btn-default" id="b3">12345</button>
<button type="button" class="btn btn-default" id="b4">12345</button>
<button type="button" class="btn btn-default" id="b5">12345</button>
<button type="button" class="btn btn-default" id="b6">12345</button>
</div>
</div>
</div>
</body>
Someone who could help me? Thanks.
Upvotes: 6
Views: 28612
Reputation: 688
I hope this will help you because it works perfectly for me
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".btn").each(function(){
$(this).click(function(){
$(this).addClass("active");
$(this).siblings().removeClass("active");
});
});
});
</script>
Try this one
Upvotes: 0
Reputation: 803
if .active
class should not be removed from active button after clicking on it please use addClass
instead of toggelClass
$("#header .btn-group[role='group'] button").on('click', function(){
$(this).siblings().removeClass('active')
$(this).addClass('active');
})
it is also good practice to narrow buttons selection, I used #heade
id and .btn-group[role='group']
which makes script applied only on buttons inside all button groups iside <div id="header"></div>
and here you have .active
class definition:
.btn.active{
background-color: red;
}
Upvotes: 5
Reputation: 932
You should use a combination of .each() and .click() here. So it will target every button in stead of only the first
$('#header .btn').each(function(){
$(this).click(function(){
$(this).siblings().removeClass('active'); // if you want to remove class from all sibling buttons
$(this).toggleClass('active');
});
});
Upvotes: 0
Reputation: 4288
You are looking for something like:
$('.btn').on('click', function(){
$(this).siblings().removeClass('active'); // if you want to remove class from all sibling buttons
$(this).toggleClass('active');
});
Upvotes: 3