I have three buttons, and want to change the color of the button on being selected. As you will see, I am able to change the color on selection, but I need buttonA to return to its original color when buttonB is selected (at which point buttonB should take on the selected color) and so on. Currently each button selected takes on the selected color, but buttons do not return to their original color.
Please see this fiddle: http://jsfiddle.net/Fwqv8/
This is the script:
jQuery(document).ready(function(){
jQuery('button.account').click(function() {
jQuery(this).removeClass("account");
jQuery(this).addClass("btn-success");
});
});
Ideally there will be a default button (buttonA) which has the selected color when the page loads initially.
Help would be greatly appreciated. Thank you.
You could remove the btn-success class on all buttons in the onclick function, then add the class only to the newly selected
jQuery(document).ready(function(){
jQuery('button.account').click(function() {
jQuery('button.btn-success').removeClass('btn-success');
jQuery(this).removeClass("account");
jQuery(this).addClass("btn-success");
});
});
Or you could have an array with the currently selected buttons, and removing the btn-success class on a newly clicked button
http://jsfiddle.net/Fwqv8/3/
jQuery(function(){
var $acctButtons = jQuery(".account");
jQuery('button.account').click(function() {
$acctButtons.removeClass("btn-success");
jQuery(this).addClass("btn-success");
});
});
YOU CAN USE TOGGLECLASS
FOR SINGLE BUTTON
LIVE DEMO
You can use:
jQuery(document).ready(function(){
jQuery('button.account').click(function(){
var that = this;
jQuery('button.account').each(function(i, btn){
jQuery(this).addClass("btn-danger");
jQuery(this).removeClass("btn-success");
});
jQuery(that).addClass("btn-success");
});
});
This code does all your buttons switch back to their default state on click. Only the clicked button will stay (in your case) "green".
An default button can easily been done by setting the default class in your markup.
JS
jQuery(document).ready(function() {
$('.btn').click(function() {
$('.btn').removeClass("btnSelected");
$(this).addClass("btnSelected");
})
});
CSS
.btn{
width:100px;
height:20px;
display:inline-block;
background-color:red;
}
.btnSelected{
background-color:green;
}
HTML
<div id="btn1" class="btn">Button 1</div>
<div id="btn2" class="btn">Button 2</div>
<div id="btn3" class="btn">Button 3</div>
Try @ codebins