user image

Mohamed Aboelfotoh
Published in : 2022-02-12

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" >Random button</button> </body></html>

Comments

Mohamed Atef Date : 2022-02-12

Best answers

51

Best answers

51

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>

 

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Display JSON in HTML using jQuery
Publish date: 2022-01-30 | Comments: 2

Tag: jQuery

Accessing Radio button values using Jquery
Publish date: 2022-03-05 | Comments: 1

Tag: jQuery

[solved] SyntaxError: Unexpected token o in JSON at position 1 jQuery
Publish date: 2022-01-30 | Comments: 2

Tag: jQuery

How to use !important using jQuery css function?
Publish date: 2022-01-27 | Comments: 2

Tag: jQuery

[SOLVED] jQuery .click() not working with auto added buttons
Publish date: 2021-06-19 | Comments: 2

Tag: jQuery

jQuery Selector is not working .click
Publish date: 2022-02-21 | Comments: 1

Tag: jQuery

How to get the style of element in jQuery? add it to another
Publish date: 2022-01-27 | Comments: 2

Tag: jQuery