user3181077
user3181077

Reputation: 313

Toggled button using javascript and css class

I am trying use toggle script on button through using css class.

Problem: When I click on the button2 it get auto selected button3 which is not correct.

Only at a time will active one button on click.

function togbtn9() {
  $("#b1").toggleClass("blueback greyback");
  $("#b2").toggleClass("blueback greyback");
  $("#b3").toggleClass("blueback greyback");

}
.greyback {
  background-color: rgb(240, 240, 240) !important;
  color: #000000;
}

.f9 {
  font-size: 0.9em !important;
}

.noround {
  border-radius: 0px 0px 0px 0px !important;
  box-shadow: 0px 0px 4px #CCCCCC;
}

.blueback {
  background-color: rgb(10, 102, 60) !important;
  color: #FFFFFF !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />

<div class="col-12 f9">
  <div class="btn-group">
    <button type="button" id="b1" onclick="togbtn9()" class="btn blueback f9 noround">Button1</button>
    <button type="button" id="b2" onclick="togbtn9()" class="btn f9 greyback noround">Button2</button>
    <button type="button" id="b3" onclick="togbtn9()" class="btn f9 greyback noround">Button3</button>
  </div>
</div>

Upvotes: 0

Views: 59

Answers (1)

Andrew L
Andrew L

Reputation: 5486

When you click Button2 all buttons are getting toggled. This means button1 is toggled off, button2 is toggled on, and button3 is toggled on.

A simpler approach is to just remove the blueback class from all buttons and then apply it to the button that was pressed. See the below example.

In the example I also converted the onclick to a jQuery event handler so it's easier to maintain later if you add more buttons for example.

$(".btn").on("click",togbtn9);

function togbtn9() {
  $(".blueback").removeClass("blueback");
  $(this).addClass("blueback");
}
.greyback {
  background-color: rgb(240, 240, 240) !important;
  color: #000000;
}

.f9 {
  font-size: 0.9em !important;
}

.noround {
  border-radius: 0px 0px 0px 0px !important;
  box-shadow: 0px 0px 4px #CCCCCC;
}

.blueback {
  background-color: rgb(10, 102, 60) !important;
  color: #FFFFFF !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />

<div class="col-12 f9">
  <div class="btn-group">
    <button type="button" id="b1" class="btn blueback greyback f9 noround">Button1</button>
    <button type="button" id="b2" class="btn f9 greyback noround">Button2</button>
    <button type="button" id="b3" class="btn f9 greyback noround">Button3</button>
  </div>
</div>

Upvotes: 1

Related Questions