Bootstrap/Javascript/JQuery make buttons change color one a time
Solution 1
Here is the most elegant way to do this:-
$('.button').click(function() {
$('.button').removeClass('btn-success').addClass('btn-primary ');
$(this).addClass('btn-success').removeClass('btn-primary ');
});
Solution 2
Make use of a class. First remove
the class from all the elements with class="btn"
then add to the particular button
which is clicked.
$('.btn').on('click',function(){
$('.btn').removeClass('clr').addClass('clr2');
$(this).removeClass('clr2').addClass('clr');
})
See fiddle.
Solution 3
Try this :
HTML
<input type="button" class="btn btn-default" value="hello">
<input type="button" class="btn btn-default" value="hello">
<input type="button" class="btn btn-default" value="hello">
JS
// this will find all input with type button
// You can place any selector, in this case your button
// better put class name for all button, and target it name
$('input[type="button"]').on('click', function(){
$('input[type="button"]').removeClass('btn-warning');
$(this).toggleClass('btn-warning');
});
buster
Updated on June 06, 2022Comments
-
buster almost 2 years
I have multiple (bootstrap)buttons in a page and I want only one of them to change color when clicked. Thus, If a button was previously clicked and received another color and now a new button is clicked the previous one should return to the normal color and the new one should change. (I hope I explained it right)
I now that it is possible with JQuery to change an elements class, ex. when clicked change from btn-primary to btn-success class(thus change color), but that requires the button to have an ID.
$("#td_id").attr('class', 'newClass');
1) So, how can I iterate through all the buttons, to check their class and change it if needed ?
2) Is there a more elegant solution ?