.css
function in jQuery takes a CSS property name and a value as parameters. For instance,
$(this).css('background-color', '#0F89BE')
It does not support adding a new class to an element. To add a class, you should use the addClass
method:
$(document).ready(function() {
$("button.btn.btn-default").on('click', function() {
$(this).addClass('active');
});
});
.active {
background-color: #0F89BE;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-default" role="button" value="50">
$50
</button>
To toggle the class when clicking the button again, you can use toggleClass
:
$(document).ready(function() {
$("button.btn.btn-default").on('click', function() {
$(this).toggleClass('active');
});
});
.active {
background-color: #0F89BE;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-default" role="button" value="50">
$50
</button>
If you only want one button to have the .active
class at a time, you can use removeClass
on all buttons before adding the class with addClass
:
$(document).ready(function() {
const btns = $("button.btn.btn-default");
btns.on('click', function() {
btns.removeClass('active');
$(this).addClass('active');
});
});
.active {
background-color: #0F89BE;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-default" role="button" value="50">
$50
</button>
<button class="btn btn-default" role="button" value="50">
$60
</button>