Mohamed Aboelfotoh
Published in : 2022-02-12
So I'm trying to use Jquery to change the classes of bootstrap buttons when I click on them using the toggleClass, but the problem is that I can only toggle between two classes, which isn't what I want. I want to toggle between at least five classes, if not more, each time I click on the button, but I can't seem to find a way to do it.
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<script>
$(document).ready(function () {
$("button").click(function () {
$(this).toggleClass("btn btn-success btn btn-info btn btn-primary");
});
});
</script>
<body>
<button id="p" >Random button</button>
</body>
</html>
You will need to use addClass instead of toggleClass so the <script> should look like
<script>
$(document).ready(function () {
$("button").click(function () {
$(this).addClass("btn btn-success btn btn-info btn btn-primary");
});
});
</script>
Join our community and get the chance to solve your code issues & share your opinion with us
Sign up Now