Utilized JavaScript and CSS class to create a toggleable button

I am attempting to implement a toggle script on a button by using a CSS class.

Issue: When I click on button2, it automatically selects button3, which is incorrect.

Only one button should be active at a time upon clicking.

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>

Answer №1

By clicking on Button2, all buttons will toggle - this means Button1 will turn off, Button2 will turn on, and Button3 will also turn on.

An easier method is to remove the blueback class from all buttons and then add it to the button that was clicked. Take a look at the example below.

In this instance, I have also switched the onclick to a jQuery event handler for easier maintenance in the future if more buttons are added, 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to maintain the toggleClass event state once an ajax call has been made?

If I have the HTML code below <div class="row"> <div class="link grey"> <a href="#">Link</a> </div> </div> <div class="row"> <div class="link"> <a href="#">Link</a> </div> & ...

Utilizing Material UI (mui) 5.0 within an iframe: Tips and tricks

Attempting to display MUI components within an iframe using react portal has resulted in a loss of styling. Despite being rendered within the iframe, MUI components seem to lose their visual appeal when displayed this way. Most resources discussing this is ...

Utilize external cascading style sheets (CSS) to style XML data loaded into Flash

Trying to incorporate formatted xml into a flash game has been quite challenging for me. Despite my efforts, the css styling doesn't seem to be applied properly. Below is the content of my stylesheet woorden.css: .f {color:red;} This is the str ...

I am experiencing an issue where the submit button in my HTML form is unresponsive to clicks

Welcome to my HTML world! <form action="petDetails.php" id="animalInput"> <ul> <li> <label for="dogName">Enter Dog's Name:</label><input id="dogName" type="text" name="dogName" /> </l ...

I am curious about why I am unable to utilize inline functions in component props. Could you please provide a detailed explanation and perhaps give an example to illustrate? Furthermore, what is

Please take note: The component prop accepts a component, not a render function. Do not pass an inline function (e.g. component={() => }), as this will cause your component to unmount and remount, losing all state when the parent component re-renders. F ...

"Utilizing Vue.js to make an AJAX request and trigger another method within a

How can I include another method within a jQuery ajax call? methods : { calert(type,msg="",error=""){ console.log("call me"); }, getData(){ $.ajax({ type: "GET", success: function(data){ / ...

Using Node.js to generate several MongoDB documents by iterating through JSON data submitted via POST requests

When a webpage sends JSON data via POST to my Node.js App (MEAN-environment using Mongoose), the format of the JSON file is as follows: Firstname: 'XY', Surname: 'asd', Articles: [ { title: '1', description: ...

What methods can a web server or website use to trigger the re-caching of its own content?

We have recently launched a simple HTML and JS website that requires frequent updates to be reflected to users quickly. However, we are facing challenges with users having to clear their caches. We are exploring options within the HTML file or the Apache w ...

the correct data format for posting using axios

I am looking to use axios for posting data in a specific format using jQuery's ajax post method. https://i.stack.imgur.com/SwKuS.jpg var data = {}; data.params = querystring.stringify({'cmd': 'getUnreadCount', 'isNewAdmin&ap ...

How to Build a Bootstrap Table using PHP and JSON Data?

Trying to use json data like this https://i.sstatic.net/iRUUE.png {"endpoint":"127.0.0.1","id":1,"identifiers":["license:LICENSEKEY","xbl:XBLKEY","live:LIVEKEY","discord:DISCORDID&q ...

Design HTML dropdown menu

I have a sleek menu design with rounded buttons, and I am looking to extend the same style to the dropdown list. I have experimented with various approaches but there are two specific issues that I need assistance with: 1. Achieving rounded corners simil ...

Ways to achieve outcomes from functions employing concatMap within rxjs?

When calling two functions, I make use of fn1 and fn2. To execute them one after the other, I utilize concatMap. I choose not to use exhaustMap and switchMap as they can result in nested "callback-hell". exhaustMap(() => fn1().pipe( swit ...

Forwarding requests via middleware in next.js 13 AppDir: true

I am currently working on implementing a redirect feature in next.js 13 when the jwt back-end is not received. This is being done with the appdir activated. This is the code in my middleware.ts file: import { NextResponse } from 'next/server' im ...

What is the best way to align and adjust the position?

I'm attempting to attach a button to a page. I may not be an expert, but here's what I have so far: body { width:100%; height:100%; background:#181516; overflow:hidden; position:absolute; } .bg { background:url(../im ...

Exploring Selenium with Java: Uncovering the Method to Locate and Identify a Specific Nested Element When Sharing Identical Parent Elements

If I have a page structured like this: <div class = "A"> <h1>AA</h1> <p>This</p> </div> <div class = "A"> <h1>BB</h1> <p>This</p> </div> And each time the page is loaded ...

Creating a pros and cons form for users using jQuery involves dynamically checking and updating the input values to ensure that no

When a new value is entered into the input box in this code, it will add and replace it for all P's tag. The desired change is to create a div with .pros-print class after each other, where the content of the P tags is equal to the new input value whe ...

Building a versatile memoization function in JavaScript to cater to the needs of various users

There is a function in my code that calculates bounds: function Canvas() { this.resize = (e) => { this.width = e.width; this.height = e.height; } this.responsiveBounds = (f) => { let cached; return () => { if (!cache ...

What is the best way to assign a unique color to two overlapping cells in an HTML table using HTML and jQuery?

I have a task to highlight a row or column when a checkbox is selected, similar to the example shown in the image below. How can I adjust the code so that the overlapping cell gets a different color instead of green or yellow? For instance, in the image b ...

"Implementing AngularJS bidirectional data binding to dynamically link user inputs with corresponding fields

Having trouble automatically outputting data with angularJS. One of the great features of angular is two-way data binding, but I can't seem to bind input with a JSON file. What I want to achieve is if the user's input matches a key, the correspon ...

Angular animation will be triggered when the user clicks using ng-click

In my Angular project, I'm looking to implement an animation that will enlarge the size of an image. Below is the code snippet: <div class="card"> <div class="item images-parent"> <img src="img/carryout-icon.jpg" class="left-image" ...