Adding and removing an active class on a button with jquery onclick function

I actually use this group of bootstrap buttons. Now, when I click on it, I need to add a class to each button. And remove from it when I click on another button.

This is my HTML structure, something like this:

<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> 

Anyone who could help me? Thanks.

+5
source share
4 answers

If the .active class .active not be removed from the active button after clicking, use addClass instead of toggelClass

 $("#header .btn-group[role='group'] button").on('click', function(){ $(this).siblings().removeClass('active') $(this).addClass('active'); }) 

Jsfiddle example

Good practice is to narrow down the selection of buttons, I used #heade id and .btn-group[role='group'] , which makes the script apply only to buttons inside all button groups iside <div id="header"></div>

and here you have the class definition .active :

 .btn.active{ background-color: red; } 
+4
source

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'); }); 

Check jsFiddle

+3
source

Here you should use a combination of .each () and .click (). Thus, it will target each button instead of 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'); }); }); 
0
source

Hope this helps you because it works great 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

0
source

All Articles