Home > Net >  how to change button class when i click on it using Jquery?
how to change button class when i click on it using Jquery?

Time:02-13

so I am using Jquery to try and change bootstrap buttons classes when I click on them using the toggleClass but the problem is I only can toggle between only 2 classes and that not what I want, I want to toggle between at least 5 classes or even more each time I click on the button, but I can't find a way to do it

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8" />
    <title>toggle</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>
  <style>
    #p {
      position: absolute;
      top: 50%;
      left: 50%;
    }
  </style>
  <body>
    <button id="p" >Random button</button>
  </body>
</html>

CodePudding user response:

You could increment a counter each time the button is clicked and add a class based on the count. 0 = green, 1 = red. Toggle is only for switching between two states like a physical toggle would

CodePudding user response:

You can put all the classes you want to apply into an array and store the array index of the currently applied class in a variable or using jQuery's .data() method.

Then, whenever the button is clicked, you retrieve and increase the index to get the next class and apply it to the button. Try this

$(document).ready(function () {
    var classes = ['btn-success', 'btn-info', 'btn-primary'];

    $("button").click(function(){
        let idx = $(this).data('class-index') ?? 0; // index of the currently applied class
        let cls = classes[idx 1] ?? classes[0]; // get the next class
        $(this).data('class-index', classes.indexOf(cls)); // store the class index
        $(this).removeClass(classes).addClass(cls); // remove old class and apply new one
    });
});
button { outline: none!important; }
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<button id="p" >Random button</button>

  • Related