tips on customizing buttons within form groups

I have set up two separate form-groups:

My goal is to click on each button within each group and toggle its style from grey to green, and vice versa. However, when I click on a button, all buttons within the group turn grey except for the one that was clicked, which turns green. I want this button toggling functionality to occur in every form-group. Can someone please assist me with this?

$('.btn').click(function() {
  var $this = $(this);
  if ($this.parents('form-group').hasClass('btn-success')) {
    $this.removeClass('btn-success')
  } else if (!$this.hasClass('btn-success')) {
    $('.btn').removeClass('btn-success')
    $this.addClass('btn-success');

  }
});
$('this').parents('form-group').addClass()
.btn-success {
  color: #fff;
  background: green;
}

.btn-simple {
  border-bottom: 1px dashed #000;
  color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="btns">Have you changed your last name?</label>
  <div class="btns">
    <button type="button" class="btn">Yes</button>
    <button type="button" class="btn btn-success">No</button>
  </div>
</div>
<div class="form-group">
  <label for="gender">Gender</label>
  <div class="btns">
    <button type="button" class="btn btn-success">Male</button>
    <button type="button" class="btn">Female</button>
  </div>
</div>

Check out my codepen here: https://codepen.io/ksena19/pen/MqRZZK

Answer №1

It seems like all you need to do is switch between states. This solution should work since there are only two states involved.

Keep in mind that this code does not verify the current state. So, if you click on an active button, it will still toggle.

$('.btn').click(function() {
  $('.btn').toggleClass('btn-success');
});
.btn-success {
  color: #fff;
  background: green;
}

.btn-simple {
  border-bottom: 1px dashed #000;
  color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="btns">Have you changed your last name?</label>
  <div class="btns">
    <button type="button" class="btn">Yes</button>
    <button type="button" class="btn btn-success">No</button>
  </div>
</div>
<div class="form-group">
  <label for="btns">Gender</label>
  <div class="btns">
    <button type="button" class="btn btn-success">Male</button>
    <button type="button" class="btn">Female</button>
  </div>
</div>

Answer №2

To add a class to just one button identified by $this in JS code, you can simply do the following:

https://codepen.io/benCat/pen/EeJMxO

$('.btn').click(function(){
    var button = $('button');
    if (button.hasClass('btn-success')) {
        button.removeClass('btn-success')
    } else if (!button.hasClass('btn-success')) {
        $('.btn').removeClass('btn-success')
        button.addClass('btn-success');

    }
});

Answer №3

In jQuery, using $('.btn').click(function() {...} will target all buttons with the class .btn. Alternatively, you can opt to use IDs instead of classes.

<button id="btn1" ... >

and subsequently trigger the click event with $("#btn1").click()...

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

It's possible for anyone to enhance the appearance of the Download button by adding styles without compromising its functionality

Looking to enhance the style of the Download button as it appears too formal. Seeking assistance in adding some button styles to make it more stylish. The code is correct, just aiming to give the Download button a trendy look with specified styles. ...

Learn how to retrieve images from the web API at 'https://jsonplaceholder.typicode.com/photos' and showcase them on a webpage using Angular10

Using the API "https://jsonplaceholder.typicode.com/photos", I have access to 5 properties: albumId: 1 id: 1 thumbnailUrl: "https://via.placeholder.com/150/92c952" title: "accusamus beatae ad facilis cum similique qui sunt" url: "https://via.placeh ...

Problems with implementing JavaScript code in a WebView

I am currently working on an android WebView project where I have managed to change the background color to orange with this code snippet. @Override public void onPageFinished(WebView view, String url) { wv.loadUrl("jav ...

What is the most efficient method to import multiple MaterialUI components using a shared namespace without requiring the entire library to be imported

In order to prevent name mixing with other libraries, I want my MaterialUI components to be under the same namespace. For example, ensuring that <Box> references <MaterialUI.Box> and not <SomeOtherLibrary.Box>. Although it seems like a si ...

When attempting to insert a date into a MySQL database using React.js, I encountered an issue with the date format

Hey everyone, I have set the input date to dd/mm/yyyy format using moment(donors.donateDate).format('DD-MM-YYYY'). However, when I click the submit button, an error is displayed in the console stating: The specified value "23-03-2022" ...

Using Angular $resources in the query() function often results in the error message "Undefined is not a function

When I try to call the query() function using ngResource, I keep getting an error message saying "Undefined is not a function." [demo.js] var app = angular.module('StarterApp', ['ngResource']); app.factory("resourceFactory", function ...

Unlock the Power of Angular: Leveraging ViewEncapsulation.Native to Access HTML Elements

I am encountering an issue where I am receiving an error when trying to access an HTML element by ID. The problem arises when I attempt to access the classList upon a user clicking a button to apply a different style class to the element. The class list an ...

Ways to arrange an array in JavaScript or jQuery when each array record contains multiple objects

Before giving a negative vote, please note that I have thoroughly searched for solutions to this problem and found none similar to what I am facing. I am looking to alphabetically sort the array by image.name using JavaScript or jQuery: var myArray = [{ ...

Analyzing XBRL documents using JavaScript

Looking to extract information from XBRL files like the one found here, I came across a promising npm module called parse-xbrl that claims to be capable of parsing XBRL files. Here is the code snippet I used for implementation: var ParseXbrl = require(&ap ...

What kind of data type should the value property of Material UI TimePicker accept?

While reviewing the documentation, I noticed that it mentions any, but there is no clear indication of what specific data types are supported. The value sent to the onChange function appears to be an object rather than a Date object, and in the TypeScrip ...

Obtaining values from keys in React list items

getEmployeeCredits(id) { if (this.state.company_roles) { return this.state.company_roles.map(function (cr, i) { if (cr.id === id) { return cr.assigned_credits } }.bind(thi ...

substitute elements within an array using elements from a different array

Looking to swap object(s) in an array with another array while maintaining the original order. Here is arrayOne: [ { "color": "#f8edd1", "selected": true }, { "color": "#d88a ...

What is the best way to maximize the size of an image without causing the parent div to expand in height?

I have utilized the code below directly from the example provided at https://getbootstrap.com/docs/5.2/utilities/flex/#media-object. This code is meant to generate a box containing an image on the left and text on the right: <div class="mycard bord ...

Trouble aligning CSS UL/LI menu in the center

Could someone help me with centering my CSS UL menu? I've posted the code below, as I'm still learning CSS and would appreciate any guidance. I've only been able to center it by setting a fixed width and using HTML center tags, but I need t ...

I'm feeling pretty lost when it comes to understanding how line-height and margins work together

When creating a webpage layout, my goal is to maintain balance by ensuring there is an equal amount of spacing between sections and elements. However, when dealing with varying font sizes and line heights, achieving this can be challenging. To provide fur ...

Avoid unnecessary re-renders in ReactJS Material UI tabs when pressing the "Enter

I've created a user interface with tabs using material-ui in reactJS. The issue I'm facing is that every time a tab is selected, the content under that tab reloads, causing performance problems because there's an iFrame displayed in one of t ...

Angular JS is failing to update views when passing dynamic IDs

I have implemented a method in my controller where I pass a dynamic id using the ng-init function, fetch a response through ajax calls, and try to print the response. However, I am facing an issue as the response is not getting printed. I am using ng-repea ...

Exploring the keyof operator in Typescript for object types

Is there a way to extract keys of type A and transfer them to type B? Even though I anticipate type B to be "x", it seems to also include "undefined". Why does the keyof operator incorporate undefined in the resulting type? It's perplexing. I kn ...

Having trouble with the JavaScript DOM rewrite for aligning text?

function modifyTextAlignment(){ document.getElementById("th1").style.textAlign = "right"; } #th1{ text-align:left; } <table> <tr><center><th colspan="2" id="th1">List of Important Emergency Contacts</th><center></tr& ...

How can I adhere to Angular 2's naming convention for Input and Output as suggested by the styleguide?

Working with inputs and outputs while following Angular 2's styleguide naming convention Initially, my directive was defined like this: ... inputs: [ 'onOutside' ] ... export class ClickOutsideDirective { @Output() onOutside: EventEmitter ...