user

Mohamed Aboelfotoh

12 Feb 2022

jQuery alter the class of a button when I click on it?

jQuery

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="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
 />
 <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
 <script src="//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" class="btn btn-success">Random button</button>
 </body>
</html>

Comments

Mohamed Atef

12 Feb 2022

Best Answer

best answer
githubgithubgithub

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>

 

© 2024 Copyrights reserved for web-brackets.com